在 Rails 中,在两种情况下都执行块: first_or_create [英] In Rails, execute block for both conditions: first_or_create
问题描述
有人知道可以让我查找现有记录或创建新记录并执行后续代码块的 Rails 方法吗?
Anybody know a Rails method that will allow me to look for an existing record or create a new one AND execute a subsequent block of code?
示例:
Model.where(parameters).first_or_create do |m|
# execute this regardless of whether record exists or not
end
同样,find_or_create_by
方法在任何一种情况下都不执行块.
Similarly, the method find_or_create_by
does not execute a block in either scenario.
我可以使用 if-else
语句,但这会重复我的代码...
I could use if-else
statements but that will duplicate my code...
推荐答案
根据 API,您的示例中的块只会在记录不存在时执行.但是您不需要块,也不需要 if-else:
According to the API, the block in your example will only execute if the record does not exist. But you don't need a block, nor an if-else:
m = Model.where(parameters).first_or_create
m.some_method # executes regardless of whether record exists or not
请注意,对对象的某些验证可能已失败,因此 m
可能尚未持久化到数据库中.
Be aware that some validations on the object may have failed and therefore m
may not have persisted to the database yet.
这篇关于在 Rails 中,在两种情况下都执行块: first_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!