【发布时间】:2014-12-04 23:42:34
【问题描述】:
我有一个 Rails 4,它的 Post 模型通过 habtm 关系与 Tag 模型相关。 标签具有名称字段和类别字段。多个标签可以有相同的类别。
我需要一个只显示至少有一个标签属于“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 tag categories include 'foo'.all”的方法,但我想不出方法。我确定我错过了一些非常明显的东西。
【问题讨论】:
-
试试
Post.includes(:tags).where("tags.category = ?", "foo") -
@PavittarGill pry(main)> Post.includes(:tags).where("tags.category = ?", "foo") Post Load (4.2ms) SELECT "posts".* FROM "posts" WHERE (tags.category = 'foo') SQLite3::SQLException: no such column: tags.category: SELECT "posts".* FROM "posts" WHERE (tags.category = 'foo') => #
标签: ruby-on-rails activerecord has-and-belongs-to-many