使用嵌套属性的Rails中的多对多关系下拉菜单 [英] Drop-Down-Menu for Many-to-Many relation in rails using nested attributes
问题描述
我通过多对多关联拥有三个表:超市,产品和供应. 每个超市可以容纳许多产品,并且每种产品可以在许多超市中出售.关联是通过供应模型建立的.
I have three tables via many-to-many-association: Supermarket, Product and Supply. Each Supermarket can hold many products and each product can be sold in many supermarkets. The association is build via the 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
我已经创建了脚手架,并填充了Supermarket-table. 在我的产品表单中,我想使用一个(或多个)下拉菜单来选择相应的超级市场名称.目标是在创建新产品的同时,还要通过供应表创建关联. 如果我要从那里选择相应的超市,代码的形式和/或控制器外观应该是什么样的?
I have created the scaffolds and populated the Supermarket-table. In my Product form, i want to use one (or more) drop-down-menu(s) to select the correspondent Supermarket-name(s). Goal is to create a new product while also creating the association via the Supply-table. What should the code look like in form and/or controller for the products if I want to select the corresponding supermarkets from there?
推荐答案
在您的产品表单中,您需要添加此行...
In you products form you need to add this line...
<%= collection_select(:product, :supermarket_ids, SuperMarket.all, :id, :name, {}, { :multiple => true } )%>
您也不必为此使用accepts_nested_attributes,您已经建立的多对多关联应处理其余的事情.
You also shouldn't need to use an accepts_nested_attributes for this, the many to many association you already have set up should take care of the rest.
这篇关于使用嵌套属性的Rails中的多对多关系下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!