Undefined method `find_or_create '

I want to update a database record using the following command

Profile.find_or_create(fname: contact.FirstName, lname: contact.LastName, company: account.Name, title: contact.Title, user_id: contact.CreatedById, account_id: account.Id, contact_id: contact.Id, type: "contact" ) 

where Profile is activerecord model

but i get the following error

 undefined method find_or_create for Profile class 

Profile.public_methods does not show the find_or_create method, but Activerecord Api defines the above method.

What could be wrong?

+6
source share
4 answers

its find_or_create_by and its deprecated in Rails 3.

use @foo = Foo.find_by_bar("baz") || Foo.create(:bar => "baz") @foo = Foo.find_by_bar("baz") || Foo.create(:bar => "baz")

+10
source

According to the Rails 4 docs use:

 User.find_or_create_by(first_name: 'Joe') 

instead:

 User.find_or_create_by_first_name('Joe') 
+2
source

My version of Rails

 Rails -v Rails 3.1.3 

My version of Ruby

 Ruby -v ruby 1.9.2p290 

In the Rails console, I can use

 find_or_create_by method like below 1.9.2-p290 :001 > User.find_or_create_by_name("soundar") User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'soundar' LIMIT 1 => #<User id: 1, name: "soundar", age: 23, created_at: "2012-04-17 11:12:43", updated_at: "2012-04-17 11:12:43"> 
+1
source

~> Rails 4

 ["Goose Island IPA", "Dogfish Head 90 Min IPA", "Mother Earth Oatmeal Stout", "Raleigh Brewing Mocha Stout"].each do |beer| Beer.find_or_initialize_by(name: beer) end 
0
source

Source: https://habr.com/ru/post/915079/


All Articles