我正在使用inherited_resources 来干燥我的控制器,但无法弄清楚如何使特定控制器正常运行。在我的模型中,User has_one Person
. 我希望它可以选择性地嵌套,嵌套时表现为单例,不嵌套时表现为非单例。换句话说,我希望能够列出所有已知的人 (/people),获取人员 #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
...然后非嵌套 /people url 工作,但嵌套 /users/:user_id/person url 不:undefined method 'people'
如果相反,在 PeopleController 中,我使用:
belongs_to :user, :optional => true, :singleton => true
...然后嵌套的 /users/:user_id/person url 起作用,但非嵌套的 /people url 不起作用,因为它被视为单例,即使是非嵌套的:undefined method 'person'
摘要:有没有办法让inherited_resources 在通过嵌套路由访问时将资源作为单例处理,但在通过非嵌套路由访问时作为非单例处理?