Search code examples
ruby-on-railsruby-on-rails-3webformsprawnprawnto

How do I specify a response format based on a form option in Rails 3.0.x


Environment: Rails 3.0.4 and Ruby 1.9.2

I have the following form:

<%= form_tag( {:action => 'show', :format => :pdf}, :method => :post) do %>

.. list of items ...

<%= submit_tag "Show", :onclick => "return checkAllFields(4);", :remote => true %> 

<select name="format">
    <option name="HTML">HTML</option>
    <option name="PDF">PDF</option>
</select>) 

<% end %>

As you can see, I've specified the format to be 'pdf' in the URL. What I want, is to request either HTML or PDF response from the controller based on the select option. Both of the queries work individually i.e. I can render either HTML or PDF but can't make it a dynamic user selection. (I can't even make it work with two separate hard-coded buttons)

Controller code is obviously

def show
  # code to locate items here

  respond_to do |format|
    format.html
    format.pdf { render :layout => false }
      prawnto :filename => "list.pdf", :prawn => { }
  end 
end

Solution

  • I would try the following:

    First, you may need to remove the hardcoded :format => :pdf from the form tag (as it may override the option, below).

    Next, make sure the select tag is passing the right values. There's a helper you can use:

    select_tag :format, options_for_select([["HTML", "html"], ["PDF", "pdf"]], "html")
    

    which returns something like the following HTML:

    <select id='format' name='format'>
      <option value='html' selected='selected'>HTML</option>
      <option value='pdf'>PDF</option>
    </select>