Quick Ruby On Rails Tip for Nested Resources

Posted on the November 1st, 2008 under My Projects,Remodeling,Ruby on Rails by John

Just a quick tip for when you are doing nested resources….

In this example, I am building a app for a client where there is a recipient and they have many physicians. So I have a case where I have a nested resource. To keep thing DRY, I added this to my before filter where I get the recipient. This allows you to nuke the find in the show, edit, update and delete actions and retain the original use of @physician.

def get_recipient
  @recipient = Recipient.find(params[:recipient_id])
  # DRYs her up a little so you don't have a find in the show,edit,update and delete actions	
  @physician = @recipient.physicians.find(params[:id]) if params[:id]
end

Don’t forget to modify your index find, change it to reflect the nested route… In my case:

    @physicians = @recipient.physicians.find(:all)

Have any other useful tips? Let me know!

Similar Posts:

Be Sociable, Share!

Leave a Reply




XHTML::
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>