【发布时间】:2012-09-06 13:26:21
【问题描述】:
我有三个通过多对多关联的表:超市、产品和供应。 每个超市可以容纳许多产品,每种产品都可以在许多超市销售。该关联是通过 Supply-model 构建的。
超市:
class Supermarket < ActiveRecord::Base
attr_accessible :name, :address, :products_attributes
has_many :supplies
has_many :products, :through => :supplies
accepts_nested_attributes_for :products
end
产品:
class Product < ActiveRecord::Base
attr_accessible :name, :supermarkets_attributes
has_many :supplies
has_many :supermarkets, :through => :supplies
accepts_nested_attributes_for :supermarkets
end
通过供应关联:
class Supply < ActiveRecord::Base
attr_accessible :supermarket_id, :product_id
belongs_to :supermarket
belongs_to :product
end
我已经创建了脚手架并填充了超市表。 在我的产品表单中,我想使用一个(或多个)下拉菜单来选择对应的超市名称。目标是创建一个新产品,同时通过供应表创建关联。 如果我想从那里选择相应的超市,产品的表单和/或控制器中的代码应该是什么样的?
【问题讨论】:
-
所以我可以通过
collection_select-helper 解决这个问题,它工作得很好。但由于对 Rails 来说相对较新,我想知道:使用nested forms有什么区别,如 Railscast #196 中所述 - 即使用什么有什么(缺点)优势以及在哪里使用什么?
标签: ruby-on-rails ruby many-to-many nested-attributes has-many-through