Jump to content

The ultimate community for Ruby on Rails developers.


Using the build helper via Javascript

  • Please log in to reply
1 reply to this topic

#1 alfatron



  • Members
  • 1 posts

Posted 04 September 2014 - 01:21 AM

I have a link on a nested form that is calling a js.erb file.


This js.erb file is using the .build helper to create another record in a one-to-many association.


This works correctly the first time.


However, on successive calls to the js.erb file, no new records are created.  I really want it to create a new record on each call to the js.erb file, but without making any changes to the database until the form is submitted.


How can this be done?


Here is the code:




<%= form_for @house do |house| %>
  <%= house.label :address %>
  <%= house.text_field :address %>
  <%= house.fields_for :purchases do |purchase| %>
    <%= purchase.collection_select(:owner_id, Owner.all, :id, :name, {prompt: true}) %>
    <%= purchase.check_box :_destroy %>
  <% end %>
  <%= link_to image_tag('plus-icon.png'), {action: :more_owners, id: @house.id}, {remote: true} %>
  <%= house.submit %>
<% end %>




<% @house.purchases.build %>;
$("body").html("<%= j(render 'form') %>");


I'm still pretty new to Rails and this is my first posting on this forum, so my apologies if this is obvious.


Thank you



#2 pgaspara



  • Members
  • 3 posts

Posted 12 September 2014 - 06:46 PM

Instead of re-rendering the entire form, you could group all procedures within a div and have more_owners.js simple add a row or item into that div. You might be able to skip the ajax call altogether and simple insert a new row with plain javascript.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users