简体   繁体   中英

How to use the option selected in options_for_select in ruby on rails

I have this dropdown in my Rails application:

<%= select_tag(:report_id, options_for_select([["Summary1", 7], ["Summary2", 6]])) %>

The user selectes a value from the dropdown above and clicks aon a button shown below to generate a PDF :

<%= link_to 'Generate', pdf_path(format: :pdf, report: :report_id), class: 'btn btn-primary' %>

This is my controller function that gets called when the button above is clicked:

def show
  init_report_data
  respond_to do |format, report|
    format.html
    format.pdf do
      puts "***************** report id" + report.to_s + "*************************"
      case report 
      when 7
        report_name = 'summary1'
      when 6
        report_name = 'summary2'
      end

      render pdf:         "Forecast Report",
           template:    "forecast/" + report_name + ".html.erb",
           disposition: "attachment",
           :page_width  => '18in',
           :page_height => '15in'
    end
  end
end

The controller function gets called fine but the value of the parameter "report" comes up empty inside the above controller function.

What am I doing wrong here? Please help!

The problem is that you're not using a form here.

Use form_tag and keep the select_tag inside the form_tag .

Also, You will have to replace link_to with a submit button. Don't forget to include the below line inside the form to make the request to respond with pdf format.

<%= hidden_field_tag :format, :pdf %>

The reason is the link_to tag don't pass your select_tag value or any other field value. In this scenario, you've to use form and there is no other option to it.

Or use JavaScript to replace the id in url when the select option changes. Since You're trying to get the show action I assume you need to pass the id in path .

<%= form_tag forecast_report_pdf_path do %>
  <%= select_tag(:report_id, options_for_select([["Summary1", 7], ["Summary2", 6]])) %>
  <%= hidden_field_tag :format, :pdf %>
  <%= submit_tag("Generate Report") %>
<% end %>

This code worked. Thanks much for your inputs!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM