如何通过has_and_belongs_to_many关联中的关联属性过滤



我有两个模型,文章和标签,具有has_and_belongs_to_many关系。有一个简单的联接表,带有两个列,即aptric_id and tag_id,没有索引。在我的文章索引模板中,我希望能够使用选择框在特定标签上过滤特定的标签,在其中您选择标签。名称字段,并将其作为查询刺痛放在URL中,并且控制器通过该标签过滤文章。以下是我的设置,它会引发错误" sqlite3 :: sqlexception:no这样的列:articles.tag_id"。它正确地添加了?tag = urol的名称,并且控制器正确分配@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

请参阅活动记录查询接口 - 在连接表上指定条件

最新更新