Skip to content Skip to sidebar Skip to footer

Rails: Accessing A Non-instance Variable In Js.erb

I have a page that renders multiple forms. Currently, when the user submits any one of these forms, it updates (via ajax) a div on the same page with the content from the form that

Solution 1:

This is one of the classic issues of RJS templates.

Quick answer:

If you simply want to solve the problem, you could pass along some temporary id to identify the form. e.g:

# in the index
<% @peer_reviews.each.with_index do|peer_review, i| %>
  <%= render :partial => 'form', 
             :locals  => { :peer_review => peer_review, :i => i } %>
<% end %>

# then in the form (note, you don't need to specify POST in a form_for)
<div id="peer_review_form_<%= i %>">
  <%= form_for peer_review, :remote => truedo|f| %>
    <%= hidden_field_tag 'temp_id', i %>

# finally in the create js.erb$("#peer_review_form_<%= params[:temp_id] %>").remove();

Longer Answer:

That being said, while RJS templates were "the Rails way" for a long time, they've since fallen out of favor.

The more modern method is typically client side JS templates with a JSON API, rather than running server generated JS templates (RJS). This has a lot of advantages, one being that the DOM binding issue you're having right now no longer exists.

This is an example of how you might do this with pure jQuery, but there are many templating options out there.

<scriptid="peer_review_tmpl"type="text/x-jquery-tmpl"><divclass="completed_peer_review"><p>${review}</p>
    ...
  </div></script>

Then you'd create a handler and bind it to a successful ajax response. This would require that your peer_reviews#create action responded to JSON:

$('form.new_peer_review').bind("ajax:success", function(data) {
  // remove the form which triggered the creation        
  $(this).remove();

  // then render the data into a template, and append it to the list
  $("#peer_review_tmpl").tmpl(data).appendTo("#completed_peer_reviews"); 
});

Post a Comment for "Rails: Accessing A Non-instance Variable In Js.erb"