ruby - Rails find_or_create_by with/without where -
let's have model named task
. , want find_or_create_by
task.
t = task.where(done: false).find_or_create_by(title: 'epic')
this model works, create task title
equal epic , done
equal false. want query search through done
equal false, don't want new record done
equal false. how can it?
you can use called: find_or_initialize_by
. initializes record, doesn't create it. way, can override properties later on:
task = task.where(done: false).find_or_initialize_by(title: 'epic').first task.done = true # or nil or whatever want! task.save
i saved first record task.done = true
. if there more 1 record, can use each
iterate through of them, , save them all.
edit:
task.where(:done => false).first_or_initialize |task| task.done = true task.title = 'epic' end
Comments
Post a Comment