【问题标题】:Rails first_or_create ActiveRecord methodRails first_or_create ActiveRecord 方法
【发布时间】:2014-04-15 08:51:36
【问题描述】:

first_or_create/first_or_create! 方法在 Rails 中的作用是什么?

根据documentation,方法“没有描述”...

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

    来自Guides

    first_or_create

    first_or_create 方法检查 first 是否返回 nil。如果它确实返回 nil,则调用 create。当与where 方法结合使用时,这非常强大。让我们看一个例子。

    假设您想找到一个名为“Andy”的客户端,如果没有,则创建一个并另外将其锁定属性设置为 false。您可以通过运行:

    Client.where(:first_name => 'Andy').first_or_create(:locked => false)
    # => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
    

    该方法生成的SQL如下所示:

    SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
    BEGIN
    INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
    COMMIT
    

    first_or_create 返回已存在的记录或新记录。在我们的例子中,我们还没有一个名为 Andy 的客户,因此会创建并返回记录。

    first_or_create!

    如果新记录无效,您也可以使用first_or_create! 引发异常。本指南未涵盖验证,但我们暂时假设您临时添加了

    validates :orders_count, :presence => true
    

    到您的客户模型。如果您尝试创建新的 Client 而不传递 orders_count,则记录将无效并引发异常:

    Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
    # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
    

    【讨论】:

      【解决方案2】:

      获取与您指定的内容匹配的第一条记录,如果没有匹配项则创建一条记录

      【讨论】:

      • 它只是获取第一条记录而不做:“matches what you have specified”
      【解决方案3】:

      如果您检查来源,您会发现它们几乎相同。唯一的区别是第一个调用“create”方法,另一个调用“create!”。这意味着如果创建不成功,第二个将引发异常。

      【讨论】:

        【解决方案4】:

        我认为现在应该避免使用first_or_create。 (尽管它仍在Rails 6.1.1 中。)在4.0 中,他们添加了find_or_create_by 和friends,这显然是为了替换first_or_create 方法。 first_or_create 曾经在guides 中被提及,现在是not。并且不再记录in the code(从 Rails 4.0 开始)。它是在Rails 3.2.19 中介绍的。

        原因是:

        • 看起来first_or_create(attrs) 确实是first(attrs) || create(attrs),而实际上是first || create(attrs)。正确的用法是:

          Model.where(search_attrs).first_or_create(create_attrs)
          

          也就是说,它可能会让人们感到困惑。 first(attrs) || create(attrs) 是 find_or_create_by 所做的。

        • 另外,使用first_or_create 会引入一个范围,这可能会以意想不到的方式影响create 回调。

        更多信息请关注changelog(搜索first_or_create)。

        【讨论】:

          猜你喜欢
          • 2020-02-14
          • 2014-01-26
          • 1970-01-01
          • 1970-01-01
          • 2011-02-22
          • 2011-05-28
          • 1970-01-01
          • 1970-01-01
          • 2017-01-08
          相关资源
          最近更新 更多