【问题标题】:First_or_create with update on match?First_or_create 更新匹配?
【发布时间】:2013-05-01 18:25:46
【问题描述】:

我真的很喜欢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'>

我想知道如果姓氏“Johannson”不存在或不同,我如何也可以更新用户。寻找最简单的方法。与上述类似的单衬里将是理想的。

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

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    Zaid 非常接近正确。

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

    这里有详细的区别。 (注意:这适用于 Rails 3+ 和 Rails 4+)

    1. first_or_createfirst_or_initialize的区别在于_initialize使用.new方法,不保存记录 vs.create自动保存。

    2. .update.update_attributes.update_attributes 之间的区别是当你有一个值的散列时使用的,通常来自像params 这样的表单提交。另一方面,.update 可以让您轻松指定每个属性,如上图(field_column: value, field_column2: value2) 等。

    正如 Zaid 所说,但它同时适用于 .update.update_attributes,rails 数据库更新“......只有在需要进行更改时才会访问数据库......”

    【讨论】:

    • update 是一种私有方法。在这种情况下调用它会给出“NoMethodError: private method `update' called...”如果你想在一行中完成所有操作,则需要使用 update_attributes。
    • 我不确定你是如何编码的,但无论如何你都不应该有任何问题。我目前在视图和控制器中以这种格式使用它:` Session.where(user_id: @user, legal_case_id: @case).first_or_create.update(last_active: now)` 更新一直是一个公共方法。 (apidock.com/rails/ActiveRecord/Relation/update)。即使您使用 .update_attributes,它也是 Rails 3+ (apidock.com/rails/ActiveRecord/Persistence/update_attributes) 之后的 .update 的别名。所以它“几乎”应该不重要。
    • update_attributes 将在 Rails 6.1 中删除:DEPRECATION WARNING: update_attributes is deprecated and will be removed from Rails 6.1 (please, use update instead)
    【解决方案2】:

    first_or_initializeupdate_attributes 应该没问题。 Rails 足够聪明,update_attributes 只有在需要进行更改时才会访问数据库(您应该能够使用控制台/日志自己确认)。

    【讨论】:

    • update_attributes 将在 Rails 6.1 中被删除:DEPRECATION WARNING: update_attributes is deprecated and will be removed from Rails 6.1 (please, use update instead)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多