通过导轨中的相关模型属性过滤器索引视图

问题描述:

我有一个rails 4,它具有与habtm关系的Tag模型相关的Post模型。 标签有一个名称字段和一个类别字段。多个标签可以具有相同的类别。通过导轨中的相关模型属性过滤器索引视图

我需要一个视图,只显示至少有一个标签属于“foo”类别的帖子。 Foo是静态的,并且始终保持“foo”。

我已经能够使其工作在我的职位控制器使用此代码:

def myview 
    ids = [] 
    Tag.where(category: 'foo').each do |tag| 
    tag.posts.each do |post| 
     ids << post.id 
    end 
    end 
    @posts = Post.where(id: ids).all 
end 

尽管工作我的代码看起来很丑陋阅读。

我敢肯定,rails提供了一种像“@posts = Post.where标签类别包括'foo'.all”的方式,但我无法找出一种方法。我确定我错过了一些非常重要的东西。

+0

尝试'Post.includes(:tags).where(“tags.category =?”,“foo”)' – 2014-12-05 01:16:24

+0

@PavittarGill pry “FROM”posts“WHERE(tags.category ='foo') SQLite3 :: SQLException:no such column:tags.category:SELECT “posts”。* FROM“posts”WHERE(tags.category ='foo') =># TopperH 2014-12-05 05:30:38

Post.joins(:标签)。凡( 'tags.category =?', “富”)所有

在评论答案就是,比如你不想查询。通过tag,但可能希望在您的视图中包含一些与tag有关的信息。通过使用includes,您将避免N+1 problem。 (主题)> Post.includes(:tags).where(“tags.category(012)”)。