我想得到一些嵌套的参数。我有一个包含许多项目的订单,这些项目每个都有一个类型。我想从 Controller 创建方法中获取 type_id 参数。
@order = Order.new(params[:order])
@order.items.each do |f|
f.item_type_id = Item_type.find_by_name(f.item_type_id).id
end
原因是我希望用户能够在 View 中创建新的 item_types。当他们这样做时,我使用 AJAX 调用将它们添加到数据库中。当他们发布表单时,我在 item_type_id 参数中获取 item_type 的名称,我想找到正确的 item_type 并将 id 设置为
最佳答案
从 params
访问嵌套字段执行以下操作:
params[:order][:items_attributes].values.each do |item|
item[:type_id]
end if params[:order] and params[:order][:items_attributes]
仅当您声明了正确的关联和
accepts_nested_attributes_for
时,上述解决方案才有效。 .class Order < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items, :allow_destroy => true
end
class Item < ActiveRecord::Base
belongs_to :order
end
关于ruby-on-rails - 如何访问嵌套参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2610263/