asdlfkjlkj
asdlfkjlkj

Reputation: 2348

Rails find all records for a collection of records

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

For the association above I need to do following query.

@posts = Post.includes(:categories).where(active: true)
@categories = @posts.categories

Obviously this query @categories = @posts.categories does not work but how would I do this?

Update: With both answers below I get this error

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")

Upvotes: 0

Views: 1578

Answers (3)

jpheos
jpheos

Reputation: 458

First you need declare relations:

In your Categorization model you need to have

belongs_to :post

And in your Category model

has_many :categorizations
has_many :posts, through: :categorizations

If you forget this, active record suppose that post is a column of Category because you never tell him that is a relation

Upvotes: 0

CV-Gate
CV-Gate

Reputation: 1170

In one query:

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

Upvotes: 0

jvillian
jvillian

Reputation: 20263

To your Category class, add:

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

Then you can do something like:

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

Upvotes: 1

Related Questions