开发者

Ajax page.replace_html problems with partials in Rails

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 f开发者_Go百科irst.

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

Thanks in advance!


Change your

<div id="postlikes">

to

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

And then,

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜