ROR + Ransack:使用按钮或link_to过滤

时间:2017-10-12 07:53:37

标签: ruby-on-rails ruby search ruby-on-rails-5 ransack

我已经引用了这两个stackoverflow帖子,但我似乎无法使用" CategoryName"填充q[categories_name_cont]。在我的网址:/articles/browse?utf8=✓&q[categories_name_cont]=&commit=CategoryName之后,我点击了名为" CategoryName"的按钮。例如。

1)Rails filter with button or link_to using Ransack 2)How to construct a clickable link with a scope using Ransack and Rails

browse.html.erb

  <% @categories.each do |category| %>
    <%= search_form_for @q, url: browse_articles_path, method: :get do |f| %>
      <%= f.hidden_field :categories_name_cont %>
      <%= f.submit category.name, :class => 'btn btn-primary', :onclick => "document.getElementById('q_categories_name_cont').value = '#{category.name}'" %>
    <% end %>
  <% end %>

articles_controller.rb

  def browse
    @q = Article.ransack(params[:q])
    @articles = @q.result.includes(:categories, :users)
    @categories = Category.with_articles.order('name ASC').all
  end

更新

1)硬编码document.getElementById(&#39; q_categories_name_cont&#39;)。value =&#34; CategoryName&#34;没有导致这个网址.. 单击名为&#34; CategoryName&#34;的按钮后/articles/browse?utf8=✓&q[categories_name_cont]=CategoryName

2)我最终使用以下方法将参数传递给url:

  <% @categories.each do |category| %>
    <a class="btn btn-large btn-primary" href="/articles/browse?utf8=✓&q[categories_name_cont]=<%= category.name %>">
    </a>
  <% end %>

1 个答案:

答案 0 :(得分:0)

您需要手动填写。

<%= f.hidden_field :categories_name_cont, params[:q].try(:[], :categories_name_cont) %>
但是,它会变得很烦人。出于这个原因,我实际上已经编写了一个小宝石,可以与SimpleForm一起自动执行此操作。如果你想看看,那么你可以在这里找到它:

https://github.com/kaspernj/simple_form_ransack