I have a rails app that has some simple functionality, allowing the user to save/unsave posts.
It does this nice and ajaxy, like so:
view:
<p id="save_<%= frugle.id %>">
<%= link_to "Save", new_saveds_path(current_user.id, :post_id => post.id), :remote => true %>
</p>
controller:
class SavedsController < ApplicationController
def new
@follow = Saved.create(:user_id => current_user.id, :post_id => params[:post_id])
@post = Post.find params[:post_id]
render :update do |page|
page.replace_html "save_#{@post.id}", "#{link_to "Unsave", saveds_path(current_user.id, :post_id => @post.id), :method => :delete, :remote => true }"
end
end
This works fine and dandy. My question comes in, as sometimes, on the homepage, the user has a whole lot of posts being viewed, and occasionally the same post shows up twice. If the user goes to save this post, the RJS above will just change the first p with that particular id that it comes across then stop. Is there any way to update all the p with that id on a single page?
That makes sense right?
Thanks!
You can’t “update all the ‘p’s with that id”, because by definition only one element on the page has a given id.
However, if you give all your
<p>s a class according to their rails id, you can do what you want.Example:
Now you can do:
And get the desired effect.
edit:
Also, this assumes you’re using jQuery in your AJAX views. I strongly advise you to do so – it’s more useful than the built-in rjs.
Here’s a screencast about it: http://railscasts.com/episodes/136-jquery