用于创建与嵌套模型的多对多关系条目的表单
我的应用程序包括以下五种模型: 超市可以有不同类别的产品,这些类别的产品可以由多个品牌生产。
现在我希望在我的超市 –forms中有一个(或两个) 选择字段,我可以在其中选择一个元素,其名称出现,一个或多个元素出现在Brand中,所以这可以存储在Origin中 。
我想我可以使用collection_select
,但我如何在这里使用它?
class Supermarket :supplies end class Supply < ActiveRecord::Base belongs_to :origin belongs_to :supermarket end class Origin < ActiveRecord::Base belongs_to :category belongs_to :brand end class Category < ActiveRecord::Base has_many :origins end class Brand < ActiveRecord::Base has_many :origins end
也许,我还要调整模型……
编辑
澄清表格的结果应该是:
在编辑超市的forms中,我想选择一个类别的产品和相应的品牌,以便我知道在这个特定的超市中销售此类别中的哪个类别和哪些品牌 :
超市(表格):
超市名称: 沃尔玛
类别 (选择一个):
- 可乐(Category_ID 1)
- 玉米片(Category_ID 2)
- …
品牌 (多选)
- 可口可乐公司(Brand_ID 1)
- 百事可乐(Brand_ID 2)
- 凯洛格公司(Brand_ID 3)
- …
这应该在Origin中创建条目,如:
Supermarket_ID Category_ID Brand_ID 1 1 1 1 1 2 2 1 2 2 2 3 ...... ......
/编辑
编辑2
根据这个问题的答案,我可以通过控制台创建或选择一个条目,如下所示:
walmart = Supermarket.create(:name => "Walmart"); cornflakes = Category.create(:name => "Corn Flakes"); kellogs = Brand.create(:name => "Kellog's"); walmart.origins.create(:category_id => cornflakes, :brand_id = kellogs)
如何通过表格使用此function? 我怎么能利用select
或collection_select
或者是否还有我可以使用的另一个助手?
/编辑2
在利用多对多关系时,我也遇到过类似的问题。 一个值得注意的gem就是simple_form 。
他们为to_many关联提供了一个很好的表单帮助器。
在实际实现表单方面,我不确定我是否理解表单数据的使用方式。 无论如何,javascript和虚拟属性都是你的朋友。
编辑:
啊,我明白你在说什么。 我这样做的方法是创建一个select_field,选择类别,然后我会创建另一个select_field(设置:multiple => true),这样我就可以选择多个品牌。
<%= select_tag "supermarket[supplies][][category]" ... %> <%= select_tag "supermarket[supplies][][brands]", ... %>
接下来,您需要将所有内容关联在一起。 因此,我会创建一个处理表单提交的虚拟属性。 例如:
def supplies=(supplies_hash) # read supplies_hash and create the active records. end def supplies end
最后,如果您坚持不使用gem进行此操作,我建议您查看嵌套表单railscast。 了解所涉及的内容。