Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_or_initialize_by doesn't work with 2 columns

I am trying to insert data in my database using 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.

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

undefined method `find_or_initialize_by'

2 columns together make the unique record:

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
like image 500
Horse Voice Avatar asked Mar 12 '13 14:03

Horse Voice


1 Answers

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

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
like image 65
jvnill Avatar answered Sep 28 '22 07:09

jvnill