views:

340

answers:

3

Hello,

I am having a problem with a pretty simple AJAX call in rails. I have a blog-style application and each post has a "like" feature. I want to be able to increment the "like" on each post in the index using AJAX onclick. I got it to work; however, the DOM is a bit tricky here, because no matter what partial its looking at, it will only update the TOP partial. so if I click "like" on post #2, it will update and replace the "likes" on post #1 instead.

Code for _post partial:

<some code here...>

<div id="postcontent">
Posted <%= post.created_at.strftime("%A, %b %d")%> <br />
</div>

<div id="postlikes">
<%= link_to_remote 'Like', :url => {:controller => 'posts', :action => 'like_post', :id => post.id}%>
<%= post.like %>
</div>

code for _postlikes partial:

<div id="postlikes">
<%= link_to_remote 'Like', :url => {:controller => 'posts', :action => 'like_post', :id => @post.id}%>
<%= @post.like %>
</div>
</div>

like_post.rjs code:

page.replace_html "postlikes", :partial => "postlikes", :object => @post
page.visual_effect :highlight, "postlikes", :duration => 3

So this all works properly for the first "postcontent" div. But this is an index of posts, so if I wanted to updated the second "postcontent" div on the page, it will still replace the html of the first.

I understand the problem, I just don't know how to fix it :)

Thanks in advance!

A: 

Change your

<div id="postlikes">

to

<div id="postlikes_<%= post.id %>">

And then,

page.replace_html "postlikes_#{@post.id}", :partial => "postlikes", :object => @post
neutrino
A: 

It's because your Div ID is the same for each partial. You need to do something like this:

<div id="<%= dom_id(post) %>">

and

<div id="postlike_<%= dom_id(post) %>">

I'm not too sure how you're setting this up but you need to have unique ids for each post (and potentially post-likes).

J

Josh Pinter
A: 

Brilliant,

That is exactly what I was looking for, thanks!

cpow