方法find_something
可能返回nil
。在以下代码中,
something = find_something(id) ? find_something(id) : create_something(foo)
find_something(id)
被调用两次。我想避免这种气味。有没有办法避免此表达式中的冗余?
答案 0 :(得分:10)
这样的事吗?
something = find_something(id) || create_something(foo)
答案 1 :(得分:6)
There's not quite enough detail given to say this with confidence, though it might be this is a case for find_or_create_by
.
If this does suit, you would just do:
something = YourModel.find_or_create_by(id: id)
You can also provide a block to this, which is passed to the create method if no record is found. For example:
something = YourModel.find_or_create_by(id: id) do |instance|
# this block only gets executed on create
instance.some_new_attribute = 'goes here'
end
Hope that's useful - let me know if it suits your use case.