I made an application that has a project model. The model has some information stored in it, and a user can add comments to the project (using the comment model). In the show view of a project I want the user to be able to switch between an “info” partial (containing the project information, and a “comment” partial (containing the comments wrote on the project). I want to do this using AJAX. So I will have two buttons: Information & Comments.
Now I know how to render a partial based on a “remote link”, but I’ll also have to find out which link was clicked. So far I can render one partial when one link is clicked like so:
// In show.html.haml
= link_to("Information", :project, :id => "link_one", :remote => true)
= link_to("Comments", :project, :id => "link_two", :remote => true)
#partial_window
// In show.js.haml
$("#partial_window").html("#{j(render("comments"))}")
Now this renders the _comment.html.haml partial when I click on one of the links. What I need to know is how to check which link was clicked, and then render the appropriate partial: _info.html.haml or _comments.html.haml.
Thanks in advance for your help!
Something like this should work. We are going to use nested routes. Check out ryan’s screencast (a little old, but it gets the point across) or this more updated version about nested forms (uses the same principles). You’ll have to pay for the updated version, but I find my RailsCast subscription to be more than worth the $9/month. Also, here are the docs for examples.
config/routes.rbcomments_controller.rbviews/comments/index.js.erbThis uses a nifty thing of rails that looks for a
commentpartial and renders it for each comment in@comments. The j helper escapes javascript and pretty much inserts the rendered partial into theappendfunction.views/comments/_comment.html.erbSo we’ve now cleared the
#holdingDivand inserted our comments. Forinformation, maybe something like this:projects_controller.rbviews/project/index.js.erbviews/project/_information.html.erbThen, your remote links would be something like:
I had to make some assumptions about what your data structures were. Let me know where I’ve confused you.
Also, I am sure I have some typos, sorry for that. I did not test this, just went off the top of my head.