Yoo*_*oku 8 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,我会收到错误消息
找不到没人和账号的人
怎么能让它正常工作?
jam*_*esc 11
您可以将路径嵌套到您想要的深度,因为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,请确保您不要尝试使用它
你的评论表明你已经使用了浅路线,但这不是你在问题中发布的内容吗?
| 归档时间: | 
 | 
| 查看次数: | 4566 次 | 
| 最近记录: |