如何根据has_and_belongs_to_many关联

时间:2017-04-28 23:16:57

标签: ruby-on-rails filter associations has-and-belongs-to-many

我有两个模型,文章和标签,具有has_and_belongs_to_many关系。有一个简单的连接表,有两列,article_id和tag_id,没有索引。在我的文章索引模板中,我希望能够使用选择框过滤特定标签,您可以在其中选择tag.name字段,并将其作为查询标记放入网址,控制器按该标记过滤文章。下面是我的设置,它会抛出错误“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 %>

1 个答案:

答案 0 :(得分:1)

# 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