我有一个有趣的问题。我正在使用 Ruby 1.9.2 和 Rails 3.1.3。
我有 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