下面的示例在 Rails 3 中有效,但在 Rails 4 中失败。
原因是Relation
通过访问关联返回的现在使用实际的数据库参数,而不是插入“拥有”ID。
class Blog < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
class Post < ActiveRecord::Base
belongs_to :blog
end
b = Blog.first # provided something exists of course
query = Post.where(id: b.posts.where("'complicated query' = ''")); 1 # just to avoid printing in console
puts query.to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."id" IN (SELECT "posts"."id" FROM "posts" WHERE "posts"."blog_id" = $1 AND ('complicated query' = ''))
query.to_a
# raises the error:
# PG::UndefinedParameter: ERROR: there is no parameter $1
# LINE 1: ...M "posts" WHERE "posts"."blog_id" = $1 AND
# ^
请注意$1
子查询中的参数显然不是从主查询中提供的(因此出现错误)。
所以问题是我们现在如何在 Rails 4 中做同样的事情(最好只做最少的改动)?