我的Post对象有post_categories数组
Post.post_categories = []
对于我的所有Post对象,我需要按post_categories过滤帖子,其中包括1
像这样Post.all.where :post_categories.include? 1
我该怎么办
这些是模型
class Post < ActiveRecord::Base
has_many :categorizes
has_many :post_categories, :through=>:categorizes
accepts_nested_attributes_for :post_categories
end
class PostCategory < ActiveRecord::Base
has_many :categorizes
has_many :posts, :through=>:categorizes
end
class Categorize < ActiveRecord::Base
belongs_to :post
belongs_to :post_category
end
答案 0 :(得分:0)
您可以在已连接表的ID字段上使用连接和过滤器:
Post.joins(:post_categories).where('post_categories.id' => 1)