views:

331

answers:

1

I was working on my website when I cam across this problem, I have 100 posts in my blog and I am paginating them 10 at a time, I display the 1st 15 and display a link at the bottom which basically is implemented using the link_to_remote tag.

<%= link_to_remote "More Posts", :url => {:action => 'view' ,:id => link.to_i + 1} , :html => {:id => 'more-link'} %>

I click on that and get the next 15 posts, and append it to the container containing the 1st 15 posts through insert_html

page.insert_html :bottom, :puzzles , :partial => 'puzzles', :object => @puzzles

Now what I want is the link at the bottom of the page to update too, so that the next time the user clicks more the 3rd batch is fetched and so on. Basically something like

page.replace_html 'more-link', link_to_remote "More Posts", :url => {:action => 'view' ,:id => link.to_i + 1} , :html => {:id => 'more-link'}

Any clues as to how I can do it?

+2  A: 

You're very close.

replace_html is called with (DOM_id, options for render). Essentially you want to render the output of a link_to_remote call. But you're not passing it in a form that render can use. As Barry Hess points out replace is much better suited for this task, because most of what you're changing is the tag attributes.

Using replace_html would result in nested tags which is could cause problems. You want to replace the element entirely. Replace has the same syntax of replace_html so you would run into the same problems if you were just switch replace_html to replace.

Here's what you want:

page.replace 'more-link', :text => link_to_remote "More Posts", 
  :url => {:action => 'view' ,:id => link.to_i + 1} ,
  :html => {:id => 'more-link'}

However I'm not sure if link_to_remote is accessible from RJS. If the above doesn't work you could always do this:

page.replace 'more-link', :inline => "<%= link_to_remote 'More Posts', 
  :url => {:action => 'view' ,:id => link.to_i + 1},
  :html => {:id => 'more-link'} %>", :locals => {:link => link}
EmFi
Actually, would `page.replace` work better is it would replace the entire element, rather than just the inner HTML. Also it might be nice to create a helper method for this particular `link_to_remote` so all the URL and HTML parameters aren't repeated.
Barry Hess
@Barry, you're absolutely correct about replace vs. replace_html. In fact replace\_html is completely wrong for the job. I've updated the answer to with your advice and provided an explanation of what makes replace\_html wrong.
EmFi
The solution you gave me works perfectly, now what if I wanna have conditionals in the rjs file, basically if the value of link == -1 I wanna replace the link with a html property of disabled, how do I do that?
Shiv
Links cannot be disabled, but they can be hidden. RJS is just ruby so you could wrap it all in an if/else block, if a condition is true replace the element, otherwise remove it.
EmFi
Great works fine...Thanks!!!
Shiv