【问题标题】:Drop-Down-Menu for Many-to-Many relation in rails using nested attributes使用嵌套属性的 Rails 中的多对多关系的下拉菜单
【发布时间】: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


【解决方案1】:

在您的产品表单中,您需要添加此行...

<%= collection_select(:product, :supermarket_ids, SuperMarket.all, :id, :name, {}, { :multiple => true } )%>

您也不应该为此使用accepts_nested_attributes,您已经建立的多对多关联应该负责其余的工作。

【讨论】:

  • 这看起来很有希望:表单显示出来了,但是在发送它时我得到一个 ActiveModel::MassAssignmentSecurity::Error 我尝试的另一个解决方案是使用 fields_for 但我得到了同样的错误。
  • 我遇到了类似的事情(我将这种方法用于技能和用户)。尝试将 :supermarket_id 添加到产品的 attr_accessible 列表中。
  • 好的,成功了 :-)。在将它添加到模型时,我对安全性有些担忧,因为批量分配安全警告肯定是有原因的 - 但浏览the mass-assignment rails-guide 我认为它也不比嵌套表单更具风险。可能这里有人可以给我更多信息...
【解决方案2】:

我认为在视图中

&lt;%= f.collection_select "super_market_ids[]",@super_markets,:id,:name,{},{:multiple=&gt;"multiple'} %&gt;

我不确定 super_market_idssuper_market_ids[] 和语法只验证过一次。

如果你想要复选框类型的多选,在选择标签中有一个chosen 库可以帮助你构建更好的用户界面,

【讨论】:

  • 好的,我认为 collection_select 是要走的路——但我想从 products 表单访问 supermarkets。我必须使用哪些变量?
  • 在控制器中的产品操作编辑和新的@super_markets = SuperMarket.all
  • 抱歉,它不起作用 - super_market_ids 是 rails 自动执行的吗?
  • 准确地说:我得到一个NoMethodError 用于super_market_idsuper_markets_id 等的任意组合...
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 2020-10-06
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多