Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - using same form partial for AJAX and non-AJAX requests

I have a form partial I am using in two places to add new ingredients (in a recipe app). When I first built the app, I wanted the user to be able to add a new ingredient while they were filling out a new recipe card. I used a modal popup and AJAX so the new ingredient form pops up, gets completed, and when the submit button is clicked some jQuery hides the modal box and updates some option tags on the page.

From the recipe form I call the ingredient partial using <%= link_to 'New ingredient', new_ingredient_path, :remote => true %>. My ingredient new.html.erb file only contains a call to the partial:

<%= render 'form' %>

And the _form.html.erb looks like: (other fields snipped for brevity)

<%= form_for @ingredient, :remote => true do |f| %>
    <%= render 'shared/ingredient_error_messages' %>
    <div class="field">
        <%= f.label :name %>
        <%= f.text_field :name %>
    </div>
    <div class="field">
        <%= f.label :amount %>
        <%= f.text_field :amount%>
    </div>
    <div class="actions">
        <%= f.submit "Save ingredient" %>
    </div>
<% end %>

My problem is that I now want the user to also be able to create a new ingredient from the ingredients section of the site. Since I don't need the modal box and jQuery functionality on that part of the site, I'd rather this be treated as a vanilla HTML request. However, I don't know how to "turn off" the AJAX functionality on demand, or if this is even good practice.

I thought of passing a parameter in the links to the new ingredient form and using that to control the :remote attribute in the form. What is the best practice here? Ideally a way to control the form's remote attribute from the link, allowing me to keep my AJAX in one spot and use HTML in the other. I could easily duplicate the form as a non-AJAX version and call that, but that's not very DRY...

like image 297
Jim Avatar asked Jun 18 '12 19:06

Jim


1 Answers

How about simple:

<%= form_for @ingredient, :remote => request.xhr? do |f| %>
like image 187
jdoe Avatar answered Sep 29 '22 09:09

jdoe