Search code examples
ruby-on-railsrubyformtastic

Passing an optional parameter in formtastic url


I have a rails view for a new action. I am using formtastic to generate the form, and I optionally have a proforma template that may have been passed to the controller.

What I want to do is make sure this proforma_id gets passed through to the create method when the form is submitted

I've found a way to do it but I want to know if this is a bit hackish and if there isn't a cleaner more ruby-like way of doing it:

<% params = {:proforma_id => @proforma.id} unless @proforma.nil? %>
<%= semantic_form_for @document, :url => documents_path(params) do |f| %>

Maybe I should just put the params line in the controller ?


Solution

  • Two ways you can pass it, depending on whether you want it in the URL or if you want it in the POST data...

    As you have discovered the first way is to pass it in the url params. You could set that variable in the controller, but you could probably get away with

    <%= semantic_form_for @document, :url => documents_path(:proforma_id => @proforma.try(:id)) do |f| %>
    

    if the extra param is nill, it just won't show up, IIRC.

    The other option is to just put it in the form as a hidden variable:

    <%= hidden_field_tag :proforma_id, @proforma.try(:id) %>