2017-08-15 90 views
0
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") 
+0

你不能這樣做,因爲如果你想擁有@categories,你的代碼行需要通過'Category.someting'開始。現在你有了更正關係,你可以做'@categories = Category.joins(:posts).where(posts:{active:true})' – djothefou

回答

0

要將Category類,添加:

class Category < ActiveRecord::Base 
    has_many :categorizations 
    has_many :posts, through: :categorizations 

然後,你可以這樣做:

@posts = Post.includes(:categories).where(active: true) 
@categories = Category.where(post: @posts) 
+0

我得到錯誤。請檢查我的更新 – asdlfkjlkj

0

在一個查詢中:

@categories = Category.joins(:posts).where(posts: { active: true }) 
+0

我得到錯誤。請檢查我的更新 – asdlfkjlkj

+0

您確定您使用此代碼出現此錯誤嗎?我看不到連接。也許你沒有關聯部分到類別模型中? –

+0

添加了所有關聯 – asdlfkjlkj

0

首先,你需要聲明的關係:

在你Categorization模型,你需要有

belongs_to :post 

而在你Category模型

has_many :categorizations 
has_many :posts, through: :categorizations 

如果你忘記了這一點,主動記錄假設post是Cate的一列因爲你永遠不會告訴他這是一種關係

+0

我想我已經有了這些東西 – asdlfkjlkj