Sasha
Sasha

Reputation: 20844

How do I find or create by key and insert values

in Rails 3 it's possible to add new record if it still doesn't exist and populate another attribues something like this:

Model.find_or_create_by_title('my title', attr1: 1, attr2: 2)

so this will look the model by title

select * from models where title = 'my title'

and if it doesnt exist then it will create it with attr1 and attr2

this approach going to be deprecated because it was overwriting missing_method and new one will use hash as as key:

Model.find_or_create_by(title: 'my title', attr1: 1, attr2: 2)

BUT, the problem that attr1: 1, attr2: 2 will be searched as well and sql will looks like:

select * from models where title = 'my title' and attr1 = 1 and attr2 = 2

Now the question: How do i search model by key and if it doesnt exist create it and populate in one insert because all HACKS like find, create and then update will not work with 'Rails Way'

Thank you all

Upvotes: 0

Views: 322

Answers (2)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8132

Not sure, i understood your question but here is the answer

 Model.find_or_create_by(title: 'my title') do |a|
  a.attr1 = 1
  a.attr2 = 2
 end

You might find more information at the official rails guides: http://guides.rubyonrails.org/active_record_querying.html#find-or-create-by.

Upvotes: 1

alex
alex

Reputation: 3742

Try this one:

Model.where(title: 'my title').first_or_create(attr1: 1, attr2: 2)

Upvotes: 1

Related Questions