Question

I'm using inherited_resources to DRY my controllers, but can't figure out how to make a particular controller behave correctly. In my model, User has_one Person. I want it to be optionally nested, behave as a singleton when nested, and as a non-singleton when not nested. In other words, I want to be able to list all known people (/people), get person #5 (/person/5), and get user 10's only person (/user/10/person). The following in routes.rb:

resources :users
  resource :person
end
resources :people

...sets up the routes as I expect:

         user_person POST   /users/:user_id/person(.:format)                people#create
     new_user_person GET    /users/:user_id/person/new(.:format)            people#new
    edit_user_person GET    /users/:user_id/person/edit(.:format)           people#edit
                     GET    /users/:user_id/person(.:format)                people#show
                     PUT    /users/:user_id/person(.:format)                people#update
                     DELETE /users/:user_id/person(.:format)                people#destroy

              people GET    /people(.:format)                               people#index
                     POST   /people(.:format)                               people#create
          new_person GET    /people/new(.:format)                           people#new
         edit_person GET    /people/:id/edit(.:format)                      people#edit
              person GET    /people/:id(.:format)                           people#show
                     PUT    /people/:id(.:format)                           people#update
                     DELETE /people/:id(.:format)                           people#destroy

... so great. Now, if in the PeopleController, I use:

belongs_to :user, :optional => true

... then the non-nested /people urls work, but the nested /users/:user_id/person urls don't: undefined method 'people' If, instead, in the PeopleController, I use:

belongs_to :user, :optional => true, :singleton => true

... then the nested /users/:user_id/person urls work, but the non-nested /people urls don't because it is being treated as a singleton, even when non-nested: undefined method 'person'

Summary: Is there a way to make inherited_resources handle a resource as a singleton when accessed via a nested route, but as a non-singleton when accessed via a not nested route?

Was it helpful?

Solution

In case anyone is trying to do something similar, I ended up just abandoning inherited_resources. I'm finding I'm happier with less "magic" going on in my controllers.

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top