【问题标题】:Add a shallow resource as member of another resource添加一个浅层资源作为另一个资源的成员
【发布时间】:2015-01-09 16:37:03
【问题描述】:

我正在使用 Rails 路由,我想要类似的东西

resources :user
  member do
    resources :comments, shallow: true
  end
end

# To get the following routes
get /users/:id/comments (index)
post /users/:id/comments (create)
get /comments/:id (show)
put /comments/:id (update)
delete /comments/:id (destroy)

但是浅化不起作用,我有以下路线(更不用说用户的:id 和评论有冲突)

get /users/:id/comments
post /users/:id/comments
get /users/:id/comments/:id
put /users/:id/comments/:id
delete /users/:id/comments/:id

我知道通常推荐的做法是

resources :user
  resources :comments, shallow: true
end

# To get the following routes
get /users/:user_id/comments
post /users/:user_id/comments
get /comments/:id
put /comments/:id
delete /comments/:id

但我希望在浅化路由创建/索引上使用params 中的:id 而不是:user_idThis is usually done by using member

您可以省略 :on 选项,这将创建相同的成员 除了资源 id 值将在 params[:photo_id] 而不是 params[:id]。

有谁知道为什么在 member 指令内进行浅化处理时无法正常工作?

【问题讨论】:

    标签: ruby-on-rails ruby routing


    【解决方案1】:

    member 指令用于将成员路由添加到现有资源,而不是嵌套资源。我个人认为让:id 引用索引中的父资源并创建操作不清楚/令人困惑,但如果您真的对在控制器中使用user_id 感到困扰,您可以通过以下方式设置您的路线

    resources :user do
      resources :comments, shallow: true, except: [:index, :create, :new, :edit]
    end
    
    get '/users/:id/comments', to: 'comments#index'
    post '/users/:id/comments', to: 'comments#create'
    

    这将为您提供以下路线

    GET /users/:id/comments
    POST /users/:id/comments
    GET /comments/:id
    PUT /comments/:id
    DELETE /comments/:id
    

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      相关资源
      最近更新 更多