我正在制作一个简单的rails应用程序,它充当科威特所有购物中心和每个购物中心内商店的目录。我创建了一个商店模型和Mall模型,并建立了以下关联:
class Shop < ActiveRecord::Base
has_and_belongs_to_many :malls
end
class Mall < ActiveRecord::Base
has_and_belongs_to_many :shops
end然后我在商店和商场之间创建了一个连接表,其中包含了shop_id和mall_id。
create_table "malls_shops", force: :cascade do |t|
t.integer "shop_id"
t.integer "mall_id"
end这就是我被困的地方
发布于 2015-09-09 12:01:15
有两个选项可以将一些shops添加到mall中
-This 1将为每个添加的商店创建中间关系:
mall = Mall.first
mall.shops << Shop.find(1)
mall.shops << Shop.find(2)-This one将为您设置控制所有商店的id,如果不存在将创建关系,如果id未退出,则将删除,如果从视图控制商店,则此id非常有用,因此您只需将id发送给控制器,一旦设置了shop_ids,它将为您完成一切(添加和删除):
mall = Mall.first
mall.shops_ids = [2,3]在视图中如何控制从模型看看这个中创建和更新
https://stackoverflow.com/questions/32474219
复制相似问题