0
votes

I have referenced these 2 stackoverflow posts, but i can't seem to get q[categories_name_cont] to be populated with "CategoryName" in my url: /articles/browse?utf8=✓&q[categories_name_cont]=&commit=CategoryName after i click the button named "CategoryName" for example.

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

UPDATE:

1) Hardcoding document.getElementById('q_categories_name_cont').value = "CategoryName" didn't result in this url either.. /articles/browse?utf8=✓&q[categories_name_cont]=CategoryName after i click the button named "CategoryName"

2) I ended up using the below method to pass parameters to the 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

1 Answers

0
votes

You need to manually fill that in.

<%= f.hidden_field :categories_name_cont, params[:q].try(:[], :categories_name_cont) %>

It can get quite annoying though. For this reason I have actually written a small gem for doing this automatically together with SimpleForm. If you want to take a look, then you can find it here:

https://github.com/kaspernj/simple_form_ransack