views:

1116

answers:

3

I have this structure in my app:

USER has_one :publicprofile, :privateprofile

PUBLICPROFILE has many :emails, :phonenumbers

PRIVATEPROFILE has many :adresses, :creditcards

I would like to know how to go about having a profile page for the user where I can update his nested resources (and do it in a RESTful way). I couldn't find any docs/examples on the subject (because of that confusing has_one relation).

+1  A: 

I recommend you watch this screencast: http://railscasts.com/episodes/139-nested-resources

It definitely helped me understand what is really possible using nested routes and resources in Rails (especially the new changes in Rails 2.2).

However, I'll have to agree with Ryan Bates here, use nested resources with care.

Derek P.
+3  A: 

I believe any nesting deeper than 1-level is generally frowned upon, and can normally be avoided. Jamis Buck blogged about it a while back.

The PeepCode REST for Rails 2 screencast is quite good too, but it doesn't go extensively into nesting, just resources in general.

James Gregory
+3  A: 

In your routes.rb file, you can add your profiles as nested resources for the users using a block:

map.resources :users do |user|
  user.resources :privateprofile
  user.resources :publicprofile
end

Then you can access your profile using a URL something like this:

users/1/publicprofiles
users/1/publicprofiles/new
users/1/publicprofiles/1/edit

You can run rake routes in your terminal to get a listing of all of the nested urls that are available to you after update your routes file.

For a really in-depth explanation see this post: http://adam.blog.heroku.com/past/2007/12/20/nested_resources_in_rails_2/

Russ Johnson