Reputation: 6862
I want to upsert record in database using 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 an activerecord model
but I get following error
undefined method find_or_create for Profile class
Profile.public_methods
doesn't show find_or_create
method but Activerecord Api
defines the above method.
What might be wrong?
Upvotes: 6
Views: 8127
Reputation: 23711
As per the Rails 4 docs
use:
User.find_or_create_by(first_name: 'Joe')
instead of:
User.find_or_create_by_first_name('Joe')
Upvotes: 4
Reputation: 1370
~> 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
Upvotes: 0
Reputation: 6728
My Rails version
Rails -v
Rails 3.1.3
My Ruby Version
Ruby -v
ruby 1.9.2p290
In Rails console I am able to use the
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">
Upvotes: 1
Reputation: 9093
its find_or_create_by
and its deprecated in Rails 3.
use @foo = Foo.find_by_bar("baz") || Foo.create(:bar => "baz")
Upvotes: 11