3

我正在使用inherited_resources來幹我的控制器,但無法弄清楚如何使特定控制器的行爲正確。在我的模型中,User has_one Person。我希望它可以嵌套,嵌套時表現爲單例,當嵌套時表現爲非單體。換句話說,我希望能夠列出所有已知的人(/人),獲得人#5(/人/ 5),並獲得用戶10的唯一人(/用戶/ 10 /人)。在routes.rb中的以下內容:如何讓一個inherited_resource可選地嵌套爲一個singleton?

resources :users 
    resource :person 
end 
resources :people 

...設置路由如我所料:

  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 

...那麼大。現在,如果把PeopleController,我使用:

belongs_to :user, :optional => true 

...那麼非嵌套/人網址的工作,但嵌套/用戶/:USER_ID /人的網址不會:undefined method 'people'相反,如果在把PeopleController,我使用:

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

...然後嵌套/用戶/:USER_ID /人網址的工作,而是因爲它被視爲一個單獨的非嵌套/人網址沒有,即使是非嵌套的:undefined method 'person'

摘要:有沒有辦法讓inherited_resources處理reso當通過嵌套路由訪問urce作爲單例時,但通過非嵌套路由訪問時作爲非單例?

回答

3

如果有人試圖做類似的事情,我最終放棄了inherited_resources。我發現我很快樂,在我的控制器中發生的「魔術」越來越少。