Search code examples
ruby-on-railstemplatesrjs

Question regarding RJS and usage of link_to_remote


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?


Solution

  • 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}