3

出于解释的目的,我将使用 SQLite 创建一个全新的 Rails (3.2.13) 项目。

rails new TestApp
cd TestApp/
rake db:create
rails g model Blog name:string description:string
rake db:migrate

这是Blog模型的内容。

class Blog < ActiveRecord::Base
  attr_accessible :description, :name

  after_create :print_other_name


  private

  def print_other_name
    # Just for example, running a query here.
    blog = Blog.first
  end
end

然后打开一个rails console

1.9.3-p125 :001 > blog = Blog.where( name: 'First Blog' ).first_or_create!( description: 'This is the first blog' )

  Blog Load (0.2ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."name" = 'First Blog' LIMIT 1
   (0.1ms)  begin transaction
  SQL (63.9ms)  INSERT INTO "blogs" ("created_at", "description", "name", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Thu, 09 May 2013 11:30:31 UTC +00:00], ["description", "This is the first blog"], ["name", "First Blog"], ["updated_at", Thu, 09 May 2013 11:30:31 UTC +00:00]]
  ======>>>>>>> Blog Load (0.6ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."name" = 'First Blog' LIMIT 1
   (1.5ms)  commit transaction
 => #<Blog id: 1, name: "First Blog", description: "This is the first blog", created_at: "2013-05-09 11:30:31", updated_at: "2013-05-09 11:30:31">

在上面的代码块中,请查看查询后已经运行的INSERT查询:

Blog Load (0.6ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."name" = 'First Blog' LIMIT 1

这是Blog.first模型中的行生成的查询after_create

本来应该是一个LIMIT 1没有任何条件的简单查询,现在name在查询中添加了一个条件。经过大量测试,我意识到添加的条件是该Blog.where( name: 'First Blog' ).first_or_create!....行中提到的条件。

换句话说,我在之前使用的任何条件似乎都会自动添加到回调中运行的所有查询中。wherefirst_or_createafter_create

我无法想象为什么这是预期的行为,但如果是这样,我在任何地方都找不到它的记录。

有人对这种行为有任何见解吗?这打破了我在after_create回调中的所有查询。

4

1 回答 1

5

first_or_create整个查询包装在 where 子句定义的范围内。您可以通过两种方式解决此问题:

  1. 而不是使用first_or_createuse find_or_create_bylike

    Blog.find_or_create_by( name: 'First Blog' )
    
  2. unscoped在所有包含如下查询的回调中使用:

    def print_other_name
      # Just for example, running a query here.
      blog = Blog.unscoped.first
    end
    
于 2013-05-09T21:11:40.833 回答