gpt4 book ai didi

ruby-on-rails - First_or_create 在比赛中更新?

转载 作者:行者123 更新时间:2023-12-04 02:53:01 27 4
gpt4 key购买 nike

我真的很喜欢first_or_create方法:

# Find the first user named Scarlett or create a new one with a particular last name.
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

我想知道如果它不存在或不同,我如何也可以使用 last_name 'Johannson' 更新用户。寻找最简单的方法来做到这一点。与上述类似的单内衬将是理想的。

一种可能的方法是 using first_or_initialize combined with update_attributes .我对这种方法唯一担心的是,即使提供的字段 100% 匹配,它也会运行更新。

最佳答案

Zaid 非常接近正确。

User.where(first_name: 'Scarlett').first_or_create.update(last_name: 'Johansson')

详细的区别在这里。 (注意:这适用于 Rails 3+ 和 Rails 4+)
  • first_or_create的区别对比 first_or_initialize_initialize使用 .new方法并且不保存记录 vs .create并自动保存它。
  • .update的区别对比 .update_attributes , .update_attributes是当你有一个散列值时使用的东西,通常来自像 params 这样的表单提交。 .另一方面,.update让您轻松指定每个属性,如上所示 (field_column: value, field_column2: value2)

  • 就像 Zaid 说的,但它同时适用于 .update.update_attributes , rails 数据库更新“...仅在有更改时才访问数据库...”

    关于ruby-on-rails - First_or_create 在比赛中更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324016/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com