Rails find_or_create_by with / without where
Let's say I have a model named Task
. And I want to find_or_create_by
complete some task.
t = Task.where(done: false).find_or_create_by(title: 'epic')
This model works, but create a task with title
epic and done
false. I want the search query through done
to be false, but I don't want the new record to be done
false. How can i do this?
source to share
You can use something called: find_or_initialize_by
. It only initializes the record, it doesn't create it. This way you can override properties later:
task = Task.where(done: false).find_or_initialize_by(title: 'epic').first
task.done = true # or nil or whatever you want!
task.save
I saved the first entry from task.done = true
. If there are multiple entries, you can use each
to repeat all of them and save them all.
Edit:
Task.where(:done => false).first_or_initialize do |task|
task.done = true
task.title = 'epic'
end
source to share