Rails find_or_create_by with/without where

孤人 提交于 2020-02-02 06:50:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!