class Post < ActiveRecord::Base
has_many :categorizations
has_many :categories, through: :categorizations
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :post
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :posts, through: :categorizations
end
对于上面的关联,我需要执行以下查询。Rails找到记录集合的所有记录
@posts = Post.includes(:categories).where(active: true)
@categories = @posts.categories
显然这个查询@categories = @posts.categories
不起作用,但我该怎么做?
更新: 有了两个答案下面我得到这个错误
Category Load (1.9ms) SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
SQLite3::SQLException: no such column: categories.post: SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: categories.post: SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
你不能这样做,因为如果你想拥有@categories,你的代码行需要通过'Category.someting'开始。现在你有了更正关系,你可以做'@categories = Category.joins(:posts).where(posts:{active:true})' – djothefou