Ruby on rails RubyonRails-将where与对象数组一起使用
我的Post对象具有Post_类别数组Ruby on rails RubyonRails-将where与对象数组一起使用,ruby-on-rails,Ruby On Rails,我的Post对象具有Post_类别数组 Post.post_categories = [] 对于我的所有帖子对象,我需要按帖子类别过滤帖子,其中包括1 像这样 Post.all.where :post_categories.include? 1 我该怎么办 这些是模型 class Post < ActiveRecord::Base has_many :categorizes has_many :post_categories, :through=>:categorizes
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
class Post:分类
接受以下类别的\u嵌套\u属性\u
结束
类后分类:分类
结束
类分类
您可以在联接表的ID字段上使用联接和筛选器:
Post.join(:Post\u categories)。其中('Post\u categories.id'=>1)
仅显示两个相应的模型。。我要看看你能告诉我我问了什么吗。。我想我可以帮你。。但在需要检查如何定义关联之前…@Arup我编辑了问题tryPost.joins(:categories)。其中(“categories.id in(?),”1)
…它正在使用类别id。我需要按Post\u category\u id进行过滤,例如,如果我有两个Post,post1.Post\u categories=[1,2,3]和post2.Post\u categories=[1,4]如果我用4过滤,只显示post2。