views:

1270

answers:

1

I would like to list all posts that are connected with some specific category and classroom.

I have:

class Post < ActiveRecord::Base
  has_many :category_posts
  has_many :categories, :through => :category_posts
  has_many :classroom_posts
  has_many :classrooms, :through => :classroom_posts
end

class Category < ActiveRecord::Base
  has_many :category_posts
  has_many :posts, :through => :category_posts
end

class CategoryPost < ActiveRecord::Base
  belongs_to :category
  belongs_to :post
end

class Classroom < ActiveRecord::Base
  has_many :classroom_posts
  has_many :posts, :through => :classroom_posts
end

class ClassroomPost < ActiveRecord::Base
  belongs_to :classroom
  belongs_to :post
end

And I wanna do something like this

Post.where(["category.id = ? AND classroom.id = ?", params[:category_id], params[:classroom_id]])

It indeed is very simple task, but I don't know what I should be looking for (keywords).

It's the same problem like this, but in rails.

EDIT: I added more details to the question. This works, but only if I have both params specified. Witch is not always the case - I dont know what params would be specified.

Post.joins(:categories, :classrooms).where(["categories.id = ? AND classrooms.id = ?", params[:classroom_id], params[:category_id]])
A: 
Category.find(params[:category_id]).posts

Also take a look at the guides:

Justice
That works, thanks. But what if I have one more many-to-many association (let's say Classrooms) to that Post and I wanna find both by Category and by Classroom? Something like Post.where(["category.id = ? AND classroom.id = ?", params[:category_id], params[:classroom_id]])
Sergey
How about this:Post.where(["category_id =?", params[:category_id]).where(["classroom_id =?", params[:classroom_id]])
chap
@chap I don't have those fields in Post table. That's why I am asking. Please read the question.
Sergey
Perhaps the railsguides have the answer.
Justice