在rails 4关联集合中的任意位置插入模型

时间:2013-11-04 08:32:55

标签: ruby ruby-on-rails-3 activerecord ruby-on-rails-4

我在两个模型之间有一个典型的has_many关系,比方说OrderItem

另外,我使用的嵌套属性如下:

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.itemsActiveRecord::Associations::CollectionProxyinsert具有不同的含义。

我如何在rails 4中完成以前在rails 3中可以做到的事情?

1 个答案:

答案 0 :(得分:0)

将其转换为数组然后插入

 @order.items.to_a.insert pos, Item.new(name: name, qty: 0)