Biju
Biju

Reputation: 1008

Pass option_for_select value as a parameter in link_to in Ruby on Rails

<%= form_tag form_submit_path do |f| %>

<%= select_tag(:report_id, options_for_select(
  [["Select Report Type", 0],
  ["Report 1", 1],
  ["Report 1", 1],
  ]), id: "report_selection")) %>

<%= link_to 'Generate Report', 
              NOT_form_submit_path, 
              report_id: report_selection,
              id: 'generate_report_link', 
              class: 'btn btn-small btn-primary', 
                remote: true%>

I have a dropdown inside a form as shown above. I also have a link_to as shown above which does NOT call the form submit path but a different path instead. Now, I would like to pass the dropdown selection value as a parameter (named report_id) in my link_to. I am not sure how to do that.

I tried using report_id: report_selection as shown above and also report_id: report_id but neither of them get passed to my controller (the value comes up as nil in my controller in either case).

How can I pass the parameter in my link_to call?

Upvotes: 0

Views: 616

Answers (1)

Anand
Anand

Reputation: 6531

Please follow the explanation in commented line, this could be done with more short lines of code, but i just explained it step by step.

<script type="text/javascript">
  //$('#report_selection').change(function(){
  $('#report_selection').on('change', function(){
    // get selected value from report_id options
    var selected_val = $(this).val(); 
    // get current path of link
    var link_url = $('#generate_report_link')[0].pathname
    // append selected value in link path and define it as new link
    var new_link_url = link_url + "?report_id=" + selected_val;
    // set new path or link
    $('#generate_report_link').attr('href', new_link_url);
  })
</script>

Change link as-

<%= link_to 'Generate Report', 
              NOT_form_submit_path,
              id: 'generate_report_link', 
              class: 'btn btn-small btn-primary', 
                remote: true%>

Upvotes: 2

Related Questions