2017-08-15 82 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