Rails - display index results and show actions through ajax

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

I know that there are many excellent disables that show how to create a form that is submitted using ajax, but this time I want to use it to display the contents of my index and display actions without a link to the page

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

I believe that I need to create a show.js.erb file, and tell my index action to respond to js, ​​but I'm a little stuck in getting further. I don’t quite understand what to add to an action show or show.js.erb - it’s a little difficult to imagine what I need to do

PS - using rails 3.0.7, jquery-1.5

+8
ajax ruby-on-rails
source share
2 answers

Got this job, it was very easy at the end.

Step 1 - Add :remote => true to the links in the 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 in 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 part (which we created in step 3)

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

Now all the content is passed through ajax and it works fine.

+10
source share

I do not have a complete answer, because I'm relatively new.

But I would start by looking at the jQuery get() method. You should be able to use this to call the index or show method. These methods should return the html that you want to display in the section without the sidebar of the page. You can use the get() callback handler to place this HTML in the corresponding div on the page.

Sorry this is a little vague, but if you play with it, I bet you will find out.

+1
source share

All Articles