Rails的find_or_create_by有/无的地方 [英] Rails find_or_create_by with/without where
问题描述
让我们说我有一个名为模型工作
。我想 find_or_create_by
一些任务。
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?
推荐答案
您可以使用一种叫做:的 find_or_initialize_by
。它只是初始化记录,但不会创建它。通过这种方式,你可以替换的属性后面:
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
我只保存 task.done = TRUE
第一条记录。如果有一个以上的记录,你可以使用每个
来遍历所有这些,并保存它们。
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.
编辑:
Task.where(:done => false).first_or_initialize do |task|
task.done = true
task.title = 'epic'
end
这篇关于Rails的find_or_create_by有/无的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!