find_or_initialize_by不适用于2列

[英]find_or_initialize_by doesn't work with 2 columns


I am trying to insert data in my database using ActiveRecord.

我正在尝试使用ActiveRecord在我的数据库中插入数据。

When I use pdays = MyModel.new for initialization rather then the below find_or_initialize_by, the script runs fine. But it ONLY runs once. I need this to run daily to perform updates. When I try running the script the second time with pdays = MyModel.new, then no duplicate key constraint is raised.

当我使用pdays = MyModel.new进行初始化而不是下面的find_or_initialize_by时,脚本运行正常。但它只运行一次。我需要每天运行以执行更新。当我第二次尝试使用pdays = MyModel.new运行脚本时,不会引发重复的键约束。

Hence I am trying the below find_or_initialize_by with 2 arguments, but that gives an error:

因此我尝试使用2个参数进行下面的find_or_initialize_by,但这会产生错误:

undefined method `find_or_initialize_by'

未定义的方法`find_or_initialize_by'

2 columns together make the unique record:

2列共同创造了独特的记录:

vertica_traffic.each do |vdays|

  pdays = MyModel.find_or_initialize_by([:local_dt], vdays[:community_id])

  pdays[:local_date]       = vdays_traffic[:local_d]
  pdays[:community_id]     = vdays_traffic[:community_id]
  pdays[:uniquesters]      = vdays_traffic[:uniques]

  pdays.save

end

3 个解决方案

#1


6  

You could try:

你可以尝试:

MyModel.find_or_initialize_by_local_dt_and_comunity_id([:local_dt], vdays[:community_id])

appending the columns names by with an _and_

使用_and_附加列名称

#2


9  

If you are using rails 3.2.1 and above, the new name of the method is first_or_initialize. It is used with conjunction with where. In your case, since you are calling save, you should use first_or_create but if you want to manually call save, just replace the method and call save after

如果您使用的是rails 3.2.1及更高版本,则该方法的新名称为first_or_initialize。它与where一起使用。在你的情况下,因为你正在调用save,你应该使用first_or_create但是如果你想手动调用save,只需要替换方法并在之后调用save。

MyModel.where(local_date: vdays_traffic[:local_date], community_id: vdays_traffic[:community_id]).first_or_create do |record|
  record.uniquesters = vdays_traffic[:uniques]
end

#3


5  

I read here that in Rails 4, this is the correct syntax:

我在这里读到,在Rails 4中,这是正确的语法:

Progress.find_or_initialize_by(chore_id: chore.id, period: period[chore.frequency], account_id: chore.account_id)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/03/12/e2c665896927ebb5a24e921327da78ec.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号