我想列出與某些特定類別和教室相關的所有帖子。Rails 3查找所有關聯記錄has_many:通過
我:
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
而且我想要做這樣的事情
Post.where(["category.id = ? AND classroom.id = ?", params[:category_id], params[:classroom_id]])
這確實是非常簡單的任務,但我不知道我應該尋找(關鍵字) 。
這是像this一樣的問題,但在rails。
編輯: 我在問題中增加了更多細節。 這有效,但只有當我有兩個參數指定。女巫並非總是如此 - 我不知道會指定哪些參數。
Post.joins(:categories, :classrooms).where(["categories.id = ? AND classrooms.id = ?", params[:classroom_id], params[:category_id]])
工作,謝謝。但是,如果我有一個多對多的關聯(比如說課堂),那麼該怎麼辦?我想要按照類別和課堂來找到這兩個關聯?類似Post.where([「category.id =?AND classroom.id =?」,params [:category_id],params [:classroom_id]]) – Sergey 2010-05-09 19:04:09
這個怎麼樣: Post.where([「category_id =?」 ,params [:category_id])。where([「classroom_id =?」,params [:classroom_id]]) – Chap 2010-05-09 22:59:34
@chap我在Post表中沒有這些字段。這就是我問的原因。請閱讀這個問題。 – Sergey 2010-05-10 09:28:20