Rails 推入数组保存对象 [英] Rails push into array saves object

查看:21
本文介绍了Rails 推入数组保存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的问题.我使用的是 Ruby 1.9.2 和 Rails 3.1.3.

I have an interesting problem. I'm using Ruby 1.9.2 and Rails 3.1.3.

我有 2 个模型,为了简单起见,我们假设客户和商店.商店有很多顾客,一个顾客属于一个商店.我正在尝试为一家商店收集所有客户,并为更多客户创建一个地方,以便我稍后可以填充值.相反,在我不期望的时候调用了 customer.save.

I have 2 models, for simplification let's say customers and stores. Stores have many customers, and a customer belongs to a store. I'm trying to collect all customers for a store, and create a place for a few more that I can populate with values later. Instead, customer.save is called when I don't expect it.

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 被调用.如果您推送到一个数组是一个普通数组而不是一个关系,则不会发生这种情况.

For some reason when the customer is pushed into the array, customer.save is called. It doesn't happen if you push to an array is a plain array and not a relation.

我找到了一种解决方法,但我仍然想知道为什么会这样.解决方法:

I found a workaround, but I'm still wondering why that happens. The workaround:

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

推荐答案

<<push

ActiveRecord::Associations::CollectionProxy中调用concat

调用 concat_records

您可以在哪里看到插入的位置.

where you can see the insert taking place.

因此,对于现有记录(持久化到数据库中),运行 <<.push 会将记录插入到集合,必要时将它们持久化到数据库中.在数组上调用 <<,而不是像您在

So, with an existing record (persisted into the database), running << or .push will insert records into the collection, persisting them to the database if necessary. Calling << on an Array, not the record collection, as you're doing in

random_array << customer

调用 Ruby 的 << Array 方法,而不是等效的 AR (如您所见,在这种情况下不会发生保存).

calls Ruby's << Array method, not the AR equivalent (as you found, no save takes place in this case).

需要明确的是,您找到的解决方法或多或少与我通常处理您正在处理的情况的方式相同;我的回答更侧重于为什么 << 有这种行为.

To be clear, the workaround you found is more or less how I typically handle the situation you're dealing with; my answer focuses more on why << has this behavior.

这篇关于Rails 推入数组保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆