amo
amo

Reputation: 3200

Pass multiple parameters by link_to in rails

How can I pass multiple parameters from the view to the controller? I need to perform a request like for example:

GET "/indicators/data?country_id=5&statistic_id=12&anotherparameter_id=anothervalue, ...."

Each parameter is generated by its own link_to selection and I would like to use the parameters together to query my model.

#app/views/indicators/index.html.erb
<!--statistic select button-->
<ul id = "statistics">
   <% Statistic.all.each do |stat| %>
   <li><%= link_to stat.indicator_name, :action => "data", :controller => "indicators", :statistic_id => stat.indicator_code, remote: true %></li>
   <% end %>
</ul>

<!--country select button-->
<ul id = "countries">
   <% Country.all.each do |c| %>
   <li><%= link_to c.name, :action => "data", :controller => "indicators", :country_id => c.id, remote: true %></li>
   <% end %>
</ul>

#config/routes.rb
get 'indicators/data' => 'indicators#data'

#app/controllers/indicators_controller.rb
  def data
    @country = Country.find(params[:country_id]).name
    @statistic = params[:statistic_id]
    @queryresult = Mymodel.where(country: @country, statistic: @statistic)
    respond_to do |format|
      format.js
    end
  end

EDIT: I had come across answers that advise to do like so:

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
# => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

But in my case I have two different links one with a single parameter corresponding to foo (eg. a checkbox) and the other a single parameter for baz (eg. a dropdown) so to say. The challenge is how to pull the parameters from different links and put them together.

Upvotes: 0

Views: 7520

Answers (1)

Narasimha Reddy - Geeker
Narasimha Reddy - Geeker

Reputation: 3860

Instead of using controller, action etc you can simply use route_helper_method with params that you want to pass simply.

<li><%= link_to stat.indicator_name, indicators_data_url(countryid: "value", another_id: "value", etc: "etc"), remote: true %></li>

Read about link_to here

Upvotes: 1

Related Questions