Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - display results of index and show actions via ajax

I have a very simple Post resource with two actions, index and show. My template contains a sidebar with links to each previous post. I want the sidebar links to display their content (i.e. the results of the "show" action) via ajax

I know there are lots of excellent tuts that show you how to create a form that submits with ajax but this time I want to use it to display the contents of my index and show actions without page referesh

. Are there any decent tutorials out there that give tips on how to do this?

I reckon I need to create a show.js.erb file, and tell my index action to respond to js but I'm a little bit stuck getting any further. I don't quite know what to put in controller's show action or show.js.erb - it's a little difficult to visualise what I need to do

PS - using rails 3.0.7, jquery-1.5

like image 268
stephenmurdoch Avatar asked May 17 '11 23:05

stephenmurdoch


2 Answers

Got this working, it was very simple in the end.

Step 1 - add :remote => true to links in sidebar

#application.html.haml
%nav#sidebar
  - for post in @posts
    = link_to post.title, post_path, :remote => true
%div#main
    = yield

Step 2 - tell your controller to respond to JS on the show action

def show
  @post = Post.find(params[:id])
  @posts=Post.all # needed for sidebar, probably better to use a cell for this
  respond_to do |format|
    format.html # show.html.erb
    format.js # show.js.erb
  end
end

Step 3 - Create _post.html.haml

# _post.html.haml
%article.post
  = sanitize post.body

Step 4 - Create show.js.erb and replace the html in the #main div with the contents of the _post partial (that we created in step 3)

# show.js.erb
$("#main").html("<%= escape_javascript(render @post) %>");

Now all the content is passed via ajax and it's working fine.

like image 78
stephenmurdoch Avatar answered Nov 15 '22 17:11

stephenmurdoch


I don't have a full answer at hand, because I'm relatively new to this, too.

But, I would start by taking a look at JQuery's get() method. You should be able to use that to call the index or show method. Those methods should return the html that you want to display in the non-sidebar section of the page. You can use get()'s callback handler to place that HTML into the appropriate div on the page.

Sorry that this is a little vague, but if you play with this I bet you'll figure it out.

like image 40
CharlieMezak Avatar answered Nov 15 '22 16:11

CharlieMezak