fredp613
fredp613

Reputation: 117

rails 4.1 - rendering nested partial in JS template - local variable issue

in my controller create action i have:

if @content.save
respond_to do |format|
 @contents = Content.all
 format.html ...
 format.js
end

in my view I have:

some html ...
render partial("home/contents")

contents partial:

@contents.each do |c| 
    some html ... (image being rendered by amazon s3/cdn)
      <%= render 'action_buttons', :c => c  %>
    end

action_buttons partial: 2 submit buttons (one for create, one for delete)

This works fine when the page is loaded - however when I submit the create action in the action buttons partial, the js error: undefined local variable or method 'c'.

In my create.js.erb I have

$(".action_buttons").html("<%= j render("home/action_buttons"), :c => c %>")

so it looks like its trying to render the view correctly so the syntax is correct however the c variable is not rendering

Keep in mind that I am only doing this because if render out the contents partial, it will re-render the image in that partial that is being served by s3, so the entire page has multiple images. To avoid this I would rather render on just the action buttons.

Upvotes: 0

Views: 1131

Answers (1)

Mandeep
Mandeep

Reputation: 9173

Change your contents partial to this

<div id="contents">
  @contents.each do |c| 
    <%= render partial: "content", locals: {c: c}
  end
</div>

Your content partial would be like this:

some html ... (image being rendered by amazon s3/cdn)
<%= render 'action_buttons', :c => c  %>

Now in your create.js.erb file you will have this code:

$("#contents").append("<%=j render partial: 'content', locals: {c: @content} %>");

Update:

You can't update just actions as it's inside a loop so you have two options either to render your whole partial again or use js to target your buttons and change there content but since you don't want to render your whole partial so you are left with second option. To update links content your create.js.erb would be like this:

$("#contents").append("<%=j render partial: 'content', locals: {c: @content} %>");
$(".follow").text('following'); // give class to all of your follow buttons and then change there content to following

Upvotes: 1

Related Questions