Rails 使用 find_or_create_by、create_with 和可选链接进行更新

Rails upsert using find_or_create_by, create_with and optional chaining

我在 upsert我的模型中使用下面的代码,它工作正常但很冗长。我想通过使用 find_or_create_bycreate_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">

没有return正确输出的较短版本:

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')