0

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.items是 a ActiveRecord::Associations::CollectionProxy,并且insert具有不同的含义。

我怎样才能在 Rails 4 中完成我以前在 Rails 3 中可以做的事情?

4

1 回答 1

0

将其转换为数组然后插入

 @order.items.to_a.insert pos, Item.new(name: name, qty: 0)
于 2013-11-04T09:49:05.630 回答