This is an old revision of the document!


Caching Nested Forms

Normally, using a nested resource's url leads you to the controller of the “embedded” resource. E.g:

  map.resources :guests, :has_many => :registrations

Produces:

    guest_registrations GET    /guests/:guest_id/registrations(.:format)           {:controller=>"registrations", :action=>"index"}
                        POST   /guests/:guest_id/registrations(.:format)           {:controller=>"registrations", :action=>"create"}
 new_guest_registration GET    /guests/:guest_id/registrations/new(.:format)       {:controller=>"registrations", :action=>"new"}
edit_guest_registration GET    /guests/:guest_id/registrations/:id/edit(.:format)  {:controller=>"registrations", :action=>"edit"}
     guest_registration GET    /guests/:guest_id/registrations/:id(.:format)       {:controller=>"registrations", :action=>"show"}
                        PUT    /guests/:guest_id/registrations/:id(.:format)       {:controller=>"registrations", :action=>"update"}
                        DELETE /guests/:guest_id/registrations/:id(.:format)       {:controller=>"registrations", :action=>"destroy"}

(You can output this yourself using rake routes)

This is obviously bad if you want to use nested forms. In a nested form, the CRUD (Create, Read, Update, Delete) actions on the nested model are automatically handled for you, so there's no real need to access the nested model's controller.

  map.resources :guests do |guest|
    guest.resources :registrations, :path_prefix => ':locale/guests/:guest_id', :controller => :guests
  end

This produces:

    guest_registrations GET    /guests/:guest_id/registrations(.:format)           {:controller=>"guests", :action=>"index"}
                        POST   /guests/:guest_id/registrations(.:format)           {:controller=>"guests", :action=>"create"}
 new_guest_registration GET    /guests/:guest_id/registrations/new(.:format)       {:controller=>"guests", :action=>"new"}
edit_guest_registration GET    /guests/:guest_id/registrations/:id/edit(.:format)  {:controller=>"guests", :action=>"edit"}
     guest_registration GET    /guests/:guest_id/registrations/:id(.:format)       {:controller=>"guests", :action=>"show"}
                        PUT    /guests/:guest_id/registrations/:id(.:format)       {:controller=>"guests", :action=>"update"}
                        DELETE /guests/:guest_id/registrations/:id(.:format)       {:controller=>"guests", :action=>"destroy"}                        

Now to be sure, following the example above you'll have to make distinction in your controller between cases where the registration id is known (all operations are on a specific registration), and where it is not (all operations pertain to a guest object). But you'd have to do that too if you were using a custom made “selected_registration_id”.

TO DO: include info on nested resources (routing)

Nested Resources in Rails 2


Personal Tools