如何将inherited_resources可选嵌套为单例?

时间:2012-03-14 04:52:23

标签: ruby-on-rails-3 singleton has-one optional inherited-resources

我正在使用inherited_resources来干掉我的控制器,但无法弄清楚如何让特定的控制器正常运行。在我的模型中,User has_one Person。我希望它可以嵌套,嵌套时表现为单例,非嵌套时表现为非单例。换句话说,我希望能够列出所有已知的人(/人),获得#5(/ person / 5),并获得用户10的唯一人(/ user / 10 / person)。 routes.rb中的以下内容:

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

...然后非嵌套/人员网址工作,但嵌套的/ users /:user_id / person网址没有:undefined method 'people'如果在PeopleController中,我使用:

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

...然后嵌套/ users /:user_id / person url工作,但非嵌套/人员网址不起作用,因为它被视为单身,即使是非嵌套的:undefined method 'person'

总结:有没有办法让inherited_resources在通过嵌套路由访问时将资源作为单例处理,但是当通过非嵌套路由访问时作为非单例?

2 个答案:

答案 0 :(得分:3)

如果有人试图做类似的事情,我最终只是放弃了inherited_resources。我发现我的控制器中没有那么“神奇”了,我感到很开心。

答案 1 :(得分:0)