如何按 has_and_belongs_to_many 关联中的关联属性进行过滤

How to filter by associated attributes in a has_and_belongs_to_many association

我有两个模型,文章和标签,具有 has_and_belongs_to_many 关系。有一个简单的连接 table,有两列,article_id 和 tag_id,没有索引。在我的文章索引模板中,我希望能够使用 select 框对特定标签进行过滤,您可以在其中 select tag.name 字段并将其作为 url查询字符串和控制器通过该标签过滤文章。下面是我的设置,它抛出错误 "SQLite3::SQLException: no such column: articles.tag_id"。它正确地将 ?tag=name 添加到 url 并且控制器正确分配 @tag 但它从那里失败。我如何让它工作?

型号

# app/models/article.rb
has_and_belongs_to_many :tags

#app/models/tag.rb
has_and_belongs_to_many :articles

控制器

# app/controllers/articles_controller.rb
def index
  if params[:tag]
    @tag = Tag.find_by(name: params[:tag])
    @articles = Article.where(tag_id: @tag.id)
  else
    @articles = Article.all
  end
end

查看

# app/views/articles/index.html.erb
<%= form_tag(articles_path, method: "get") do %>
  <%= select_tag "tag", options_from_collection_for_select(Tag.all, "name"),
       prompt: "Select Tag" %>
  <%= submit_tag "Submit" %>
<% end %>
# app/views/articles/index.html.erb
<%= form_tag(articles_path, method: "get") do %>
  <%= select_tag "tag_ids", options_from_collection_for_select(Tag.all, :id, :name),
       prompt: "Select Tag", multiple: true %>
  <%= submit_tag "Submit" %>
<% end %>

# app/controllers/articles_controller.rb
def index
  if params[:tag_ids]
    @articles = Article.joins(:tags).where('tags.id' =>  params[:tag_ids])
  else
    @articles = Article.all
  end
end

Active Record Query Interface - Specifying Conditions on the Joined Tables