I am trying to pass along a local variable to a partial using link_to. I have tried many different things, but it doesn’t seem to work. The js file loads the partial fine, it just doesn’t have the locals. This is what I have, thanks for any direction!
_health.html.erb (this is a partial on index.html of Contacts model)
<% @comments = Comment.find_all_by_api(@api) %>
<%= link_to 'Read Comments', comments_path(:comments => @comments), :action => 'comments', :remote => true %>
comments.js.erb
$("#comments").html("<%= escape_javascript(render(:partial => 'comment', :locals => {:comments => :comments})) %>");
comment.html.erb
<% unless @comments.blank? %>
<% @comments.each do |c| %>
<%= c %><br />
<% end %>
<% end %>
contacts_controller.rb
def comments
respond_to do | format |
format.js {render :layout => false}
end
end
The partial does not know about the comments because you never set them. The comments action in the controller needs to look like this:
(replace
params[:id]with the appropriate parameter from your route)You’re doing an AJAX request and since http is stateless, the comments action does not know anything about any previous requests – which means that the comments from _health.html.erb have ceased to exist for the comments action in the controller.