Rails 3级深层嵌套资源

时间:2012-05-19 00:25:00

标签: ruby-on-rails ruby-on-rails-3

我知道很多铁路开发人员说将资源嵌套到2级以上是不对的。我也同意,因为当你的网址看起来像mysite.com/account/1/people/1/notes/1时,它会变得混乱。我试图找到一种方法来使用嵌套资源,但没有嵌套它们3级深。

这是错误的做法,因为rails开发人员不推荐它,并且很难弄清楚如何在控制器或窗体视图中嵌套它。

resources :account do 
  resources :people do
    resources :notes
  end
end

rails开发人员说这应该做的正确方法就是这样

resources :account do 
  resources :people
end

resources :people do
  resources :notes
end

这是我经常遇到的问题。当我访问帐户/ 1 /人我可以添加一个人到帐户,并让我们说网址是这样的mysite.com/account/1/people/1,并且工作正常。

现在,如果我尝试从帐户1访问mysite.com/people/1/notes,我会收到错误

  

找不到没有人和帐户ID的人

如何让它正常工作?

1 个答案:

答案 0 :(得分:11)

您可以将路径嵌套到您想要的深度,因为rails 3.x允许您使用浅层来展平它们:true

尝试使用

进行试验
resources :account, shallow: true do 
  resources :people do
    resources :notes
  end
end

使用rake路线查看你得到的信息:)

更新以回应评论

正如我所说,玩耙路线看你能得到什么网址

resources :account, shallow: true do 
  resources :people, shallow: true do
    resources :notes
  end
end

获取这些路线

:~/Development/rails/routing_test$ rake routes
      person_notes GET    /people/:person_id/notes(.:format)        notes#index
                   POST   /people/:person_id/notes(.:format)        notes#create
   new_person_note GET    /people/:person_id/notes/new(.:format)    notes#new
         edit_note GET    /notes/:id/edit(.:format)                 notes#edit
              note GET    /notes/:id(.:format)                      notes#show
                   PUT    /notes/:id(.:format)                      notes#update
                   DELETE /notes/:id(.:format)                      notes#destroy
    account_people GET    /account/:account_id/people(.:format)     people#index
                   POST   /account/:account_id/people(.:format)     people#create
new_account_person GET    /account/:account_id/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
     account_index GET    /account(.:format)                        account#index
                   POST   /account(.:format)                        account#create
       new_account GET    /account/new(.:format)                    account#new
      edit_account GET    /account/:id/edit(.:format)               account#edit
           account GET    /account/:id(.:format)                    account#show
                   PUT    /account/:id(.:format)                    account#update
                   DELETE /account/:id(.:format)                    account#destroy

可以看出,您可以访问您决定需要的任何级别的所有型号。其余部分归结为您在控制器操作中添加的任何内容。

你真的必须处理这些动作以确保在没有传入id params时采取适当的行动,所以如果你使用特定模型的id,那么检查id是否在params列表中,如果不采取其他行动。例如如果您未通过帐户ID,请确保不要尝试使用它

你的评论声明你已经使用了浅层路线,但这不是你在问题中发布的那个?

相关问题