problems with form_tag for controller action with members-get route

Dominic picture Dominic · Mar 6, 2011 · Viewed 21.5k times · Source

I'm making a form_tag panel that contains information (checkboxes) specific to a controller action. This action is set up in "routes.rb" as follows:

resources :students do
  collection do
    get :send_student_report_pdf
  end   
end

This setup works perfectly when I call the action from a link_to:

<%= link_to "Download PDF Report", :action => 'send_student_report_pdf', :controller => 'students'%>

However when I used it in a form_tag, it keeps giving me this error:

Routing Error
No route matches "/students/send_student_report_pdf"

The form_tag code I have is here:

<%= form_tag :controller => 'students', :action => 'send_student_report_pdf', :method => 'get' do %>
  <%= label_tag "Include columns" %> <br>
  <%= check_box_tag "first_name", params[:first_name], checked = true %> <%= label_tag "First Name" %><br>  
  <%= submit_tag "Download PDF Report", :action => 'send_student_report_pdf', :controller => 'students'%>  
<% end %>

I have tried giving it the url, path like:

<%= form_tag send_student_report_pdf_students_path, :method => 'get' do %>

But it has been consistently giving me the same Route error (as if the action doesn't exist at all in routes.rb, even though it works perfectly using link_to instead of form_tag submit

Here is the code for the action in the controller, it basically sends back a file.

def send_student_report_pdf
  @students = search_sort_and_paginate
  puts "params[:first_name] = ", params[:first_namea]
  send_data(generate_pdf_report(@students), :filename => "report.pdf", :type => 'application/pdf') 
end

If you see that I'm missing something here, please help me.

Thank you very much,

Regards,

Answer

idlefingers picture idlefingers · Mar 6, 2011

The :method => 'get' part in your form_for is in the url_for_options hash, not the options hash, so Rails will be putting it onto the url as cgi params instead. Try changing it to this:

form_tag url_for(:controller => 'students', :action => 'send_student_report_pdf'), :method => 'get' do ...

The reason you can't use the named route is because you didn't name it in your routes. If you name it in your routes and use the named route in your form_tag, you won't need to use url_for...

resources :students do
  collection do
    get :send_student_report_pdf, :as => :send_student_report_pdf
  end   
end

You can check whether your routes are as you expect by running rake routes