我在两个模型之间有一个典型的has_many
关系,比方说Order
和Item
。
另外,我使用的嵌套属性如下:
class Order < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
end
在整理嵌套的编辑订单时,我希望能够构建新项目(项目有名称和数量),并将它们插入以前保存的列表中的任意位置物品。
假设我有一个排序的字符串数组,列出all_possible_item_names
,客户可以指定数量。
直到rails 3.2.13,@order.items
是一个简单的数组,我可以使用ruby自己的Array#insert
方法在我想要的任何地方插入新项目:
# after loading the original order, this code will build additional items
# and insert them in the nested edit order form with a default qty of 0
all_possible_item_names.each_with_index do |name, pos|
unless @order.items.find { |i| i.name == name }
@order.items.insert pos, Item.new(name: name, qty: 0)
end
end
另一方面,在rails 4中,@order.items
是ActiveRecord::Associations::CollectionProxy
,insert
具有不同的含义。
我如何在rails 4中完成以前在rails 3中可以做到的事情?
答案 0 :(得分:0)
将其转换为数组然后插入
@order.items.to_a.insert pos, Item.new(name: name, qty: 0)