【问题标题】:Filter index view by related model attribute in rails通过rails中的相关模型属性过滤索引视图
【发布时间】: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


【解决方案1】:

Post.joins(:tags).where('tags.category = ?', "foo").all

评论中的答案是,例如,您不想通过tag 查询,但可能想在您的视图中包含与tag 相关的一些信息。通过使用includes,您将避免使用N+1 problem

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2020-12-21
    • 1970-01-01
    • 2011-07-06
    • 2011-11-06
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多