Rails upsert使用find_or_create_by, create_with和可选的链接



我使用下面的代码来upsert我的模型,它工作正确,但冗长。我想通过使用find_or_create_by,create_with和可选的链接来缩短它,但它没有按预期工作。

谁来指点一下……

可以工作的详细代码-

user_attr = {
first_name: 'Scarlett',
last_name: 'Johansson',
profession: 'Actress',
address: 'Los Angeles'
}
....
existing_user = User.find_by(first_name: user_attr.fetch(:first_name), 
last_name: user_attr.fetch(:last_name))
if existing_user
existing_user.update!(user_attr)
else
User.create!(user_attr)
end
Output:
# => #<User id: 2, first_name: "Scarlett", last_name: "Johansson", profession: "Actress", address: "Los Angeles">

不返回正确输出的短版本:

User
.create_with(user_attr)
.find_or_create_by(first_name: user_attr.fetch(:first_name), 
last_name: user_attr.fetch(:last_name))

参考- https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by

你可以先find_or_create_by,然后update:

user = User.find_or_create_by!(first_name: 'Scarlett', last_name: 'Johansson')
user.update!(profession: 'Actress', address: 'Los Angeles')

最新更新