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