ruby-on-rails – Rails 3级深层嵌套资源
我知道许多rails开发人员说,将资源嵌套到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,我会收到错误消息
怎样才能让它正常工作? 解决方法
您可以将路径嵌套到您想要的深度,因为rails 3.x允许您使用shallow: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参数时,你真的必须处理这些动作以确保你采取适当的行动,所以如果你使用特定模型的id,那么检查id是否在params列表中,如果没有替代行动.例如如果您未传递帐户ID,请确保不要尝试使用它 您的评论表明您已经使用浅路线,但这不是您在问题中发布的内容? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |