问题
Let's say I have a model named Task
. And I want to find_or_create_by
some task.
t = Task.where(done: false).find_or_create_by(title: 'epic')
This model works, but create a task with title
equal to epic and done
equal to false. I want query search through done
equal to false, but I don't want new record done
equal to false. How can I do it?
回答1:
You can use something called: find_or_initialize_by. It only initializes the record, but doesn't create it. This way, you can override the properties later on:
task = Task.where(done: false).find_or_initialize_by(title: 'epic').first
task.done = true # or nil or whatever you want!
task.save
I only saved the first record with task.done = true
. If there are more than one record, you can use each
to iterate through all of them, and save them all.
Edit:
Task.where(:done => false).first_or_initialize do |task|
task.done = true
task.title = 'epic'
end
来源:https://stackoverflow.com/questions/30952981/rails-find-or-create-by-with-without-where