【发布时间】:2015-02-01 06:06:54
【问题描述】:
我有以下示例模型结构:
class Category < ActiveRecord::Base
has_many :posts
scope :active, -> { where(active: true) }
end
class User < ActiveRecord::Base
has_many :posts
has_many :visible_posts, -> { joins(:category).merge(Category.active) }, class: Post
has_many :visible_posts_comments, through: :visible_posts, source: :comments
has_many :comments
end
class Post < ActiveRecord::Base
belongs_to :category
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
现在User.first.visible_posts_comments 引发以下错误:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "categories"
LINE 1: ..." = "posts"."id" WHERE "posts"."user_id" = $1 AND "categorie...
这是因为这个关联执行的SQL如下:
2.1.2 :009 > u.visible_posts_comments.to_sql
=> "SELECT \"comments\".* FROM \"comments\" INNER JOIN \"posts\" ON \"comments\".\"post_id\" = \"posts\".\"id\" WHERE \"posts\".\"user_id\" = $1 AND \"categories\".\"active\" = 't'"
虽然visible_posts 通过在categories 上添加INNER JOIN 可以正常工作,但
2.1.2 :010 > u.visible_posts.to_sql
=> "SELECT \"posts\".* FROM \"posts\" INNER JOIN \"categories\" ON \"categories\".\"id\" = \"posts\".\"category_id\" WHERE \"posts\".\"user_id\" = $1 AND \"categories\".\"active\" = 't'"
为什么visible_posts_comments 似乎“丢失”了joins(:category) 语句但保留了merge(Category.active)?我认为没有理由故意放弃 through-association 的联接。这是错误还是功能?
我正在使用 activerecord-4.1.8。
【问题讨论】:
-
如果查询使用
includes而不是joins,是否也会发生这种情况? -
@fjuan 将连接更改为包含,并且 visible_posts 也引发了相同的错误,缺少 FROM 子句
标签: ruby-on-rails rails-activerecord has-many-through