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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -