出于解释的目的,我将使用 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!....
行中提到的条件。
换句话说,我在之前使用的任何条件似乎都会自动添加到回调中运行的所有查询中。where
first_or_create
after_create
我无法想象为什么这是预期的行为,但如果是这样,我在任何地方都找不到它的记录。
有人对这种行为有任何见解吗?这打破了我在after_create
回调中的所有查询。