【问题标题】:Rails associations routingRails 关联路由
【发布时间】:2016-10-31 13:25:12
【问题描述】:

我有两个模型 BlogUser 具有以下关联

Blog belongs_to :user

我的路线如下

resources :users, shallow: true do
  resources :blogs
end

这些是生成的路由

   user_blogs GET    /users/:user_id/blogs(.:format)     blogs#index
              POST   /users/:user_id/blogs(.:format)     blogs#create
new_user_blog GET    /users/:user_id/blogs/new(.:format) blogs#new
    edit_blog GET    /blogs/:id/edit(.:format)           blogs#edit
         blog GET    /blogs/:id(.:format)                blogs#show

问题是为什么有些路由(例如new_user_blog)有正确的路由,而其他路由(edit_blog 应该是edit_user_blog)是错误的?

【问题讨论】:

  • 在嵌套的:users 资源之外是否还有resources :blogs
  • 是因为你请求了浅层路由,没有错。这就是浅路由会发生的情况

标签: ruby-on-rails ruby-on-rails-4 routing


【解决方案1】:

您获得这些路线是因为 shallow-nesting

浅嵌套只会为 indexcreatenew

生成嵌套路由

根据文档,使用 shallow 选项相当于生成如下路线:

resources :users do
  resources :blogs, only: [:index, :new, :create]
end
resources :blogs, only: [:show, :edit, :update, :destroy]

哪个会生成

    user_blogs  GET    /users/:user_id/blogs(.:format)      blogs#index
                POST   /users/:user_id/blogs(.:format)      blogs#create
 new_user_blog  GET    /users/:user_id/blogs/new(.:format)  blogs#new
     edit_blog  GET    /blogs/:id/edit(.:format)            blogs#edit
          blog  GET    /blogs/:id(.:format)                 blogs#show
                PATCH  /blogs/:id(.:format)                 blogs#update
                PUT    /blogs/:id(.:format)                 blogs#update
                DELETE /blogs/:id(.:format)                 blogs#destroy
         users  GET    /users(.:format)                     users#index
                POST   /users(.:format)                     users#create
      new_user  GET    /users/new(.:format)                 users#new
     edit_user  GET    /users/:id/edit(.:format)            users#edit
          user  GET    /users/:id(.:format)                 users#show
                PATCH  /users/:id(.:format)                 users#update
                PUT    /users/:id(.:format)                 users#update
                DELETE /users/:id(.:format)                 users#destroy

而使用shallow 选项会生成与上面完全相同的路由

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-27
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多