我有一个有趣的问题。我正在使用Ruby 1.9.2和Rails 3.1.3。Rails推入阵列保存对象
我有2个模型,简化让我们说客户和商店。 商店有许多顾客,而顾客属于商店。 我试图收集所有商店的顾客,并创建一个地方供我稍后填充值。相反,当我不期望的时候会调用customer.save。
store = Store.find(1)
customers_array = store.customers
random_array = Array.new
customers_count = customers_array.count + 1
(customers_count..2).each do |i|
customer = Customer.new
c.id = "#{i}000000000000"
random_array << customer # this line doesn't call customer.save
customers_array << customer # this line calls customer.save when store has customers
end
由于某些原因,当客户被推入数组时,customer.save被调用。 它不会发生,如果你推到一个数组是一个普通的数组而不是一个关系。
我发现了一种解决方法,但我仍然想知道为什么会发生这种情况。 解决方法:
store = Store.find(1)
initial_customers_array = store.customers
additional_customers_array = Array.new
customers_count = initial_customers_array.count + 1
(customers_count..2).each do |i|
customer = Customer.new
c.id = "#{i}000000000000"
additional_customers_array << customer
end
customers_array = initial_customers_array + additional_customers_array
对于那些寻找解决方案而不是为什么:在集合上使用''build'''来创建一个模型而不保存它:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods .html#module-ActiveRecord :: Associations :: ClassMethods-label-Collections – blu
我有相反的问题。在模型规范中使用'build',然后使用<<向集合添加项目不起作用。这个问题的答案解释了为什么不。 – CJBrew