Rails first_or_initialize,但带有条件



我有一个用户模型,包含email, name, &代码字段。电子邮件必须是唯一的。在rails中是否有一种方法可以让我一次性完成:

创建指定邮箱的用户&如果邮件还没有收到就写代码或者用该电子邮件更新用户的代码,但名称必须等于'abc'

还是这是唯一的方法?

begin
user.create!(code: ..., email:...)
rescue ActiveRecord::RecordInvalid => e
if it is email taken error
User.where(name: 'abc').update(code:...)
end
end

感谢

我想这就是我们要找的

user = User.find_by(email: ...) || User.new(email: ...)
user.assign_attributes(code: ...) if user.name == 'abc' || user.new_record?
user.save if user.changed?

您想要的是#find_or_create_by与block:

User.find_or_create_by(email: ....) do |user|
user.code = ... if user.name == 'abc'
end

如果它找到具有给定电子邮件的用户,则不调用该块。

如果它没有找到具有给定电子邮件的用户,它将调用只在名称为'abc'的条件下更新代码的块

最新更新