【问题标题】:Rails make some routes resource singular and some pluralRails 使一些路线资源单数和一些复数
【发布时间】:2020-02-13 00:36:59
【问题描述】:

我需要实现以下路径:

PUT        /group(.:format)         api/v1/groups#update {:format=>:json}
DELETE     /group(.:format)         api/v1/groups#destroy {:format=>:json}
GET        /groups(.:format)        api/v1/groups#index {:format=>:json}
GET        /groups/:id(.:format)    api/v1/groups#show {:format=>:json}

如您所见,我需要 PUT 和 DELETE 到 group(没有 id),但索引和显示到 groups 路径。

我已经在我的routes.rb 上试过这个:

resource :group, only: %i[update destroy]
resources :groups, only: %i[show index]

它似乎创建了所需的路线:

api_group PATCH      /group(.:format)          api/v1/groups#update {:format=>:json}
           PUT        /group(.:format)         api/v1/groups#update {:format=>:json}
           DELETE     /group(.:format)         api/v1/groups#destroy {:format=>:json}
api_groups GET        /groups(.:format)        api/v1/groups#index {:format=>:json}
           GET        /groups/:id(.:format)    api/v1/groups#show {:format=>:json}

但是当我为节目运行测试时,我得到:

Failure/Error: get api_group_path(group.id), headers: auth_headers, as: :json

ActionController::RoutingError:
  No route matches [GET] "/group.86d95177-9b44-4b5b-8ff7-98b609614c50"

所以我敢打赌它们一定是相互覆盖的,因为要么显示和索引工作,要么删除和放置。

有人可以帮助我吗?谢谢

【问题讨论】:

  • 您可以尝试rake routes 再次检查您的路线吗?
  • 从未尝试过,但可能添加GroupController 会有所帮助。
  • 我有一个GroupsController

标签: ruby-on-rails routes


【解决方案1】:

根据您的 GET 请求路线,您必须调用:

api_v1_groups_path(group_id) #for SHOW method
api_v1_groups_path           #for INDEX method

对于 PATCH 和 DELETE 请求,您必须调用:

api_v1_group_path

编辑: 是的,我已经检查了沙箱,路线有点乱,我的建议是用生成这样的自定义路线替换您当前的路线:

namespace :api do
  put "/group",      to: "groups#update",  as: 'update_group'
  delete "/group",   to: "groups#destroy", as: 'destroy_group'
  get "/groups",     to: "groups#index",   as: 'index_groups'
  get "/groups/:id", to: "groups#show",    as: 'show_group'
end

它会生成与您相​​同的路线:

api_update_group   PUT    /api/group(.:format)                                                                     api/groups#update
api_destroy_group DELETE  /api/group(.:format)                                                                     api/groups#destroy
api_index_groups   GET    /api/groups(.:format)                                                                    api/groups#index
api_show_group     GET    /api/groups/:id(.:format)                                                                api/groups#show

这应该可行。希望对你有所帮助

【讨论】:

  • api_v1_groups_path(group_id) #for SHOW method 不起作用。它进入索引操作。知道为什么吗?
  • 你现在的rake routes怎么样?
  • 它确实有效,谢谢。但老实说,我认为必须存在一种更好的方法来不使用自定义路由。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2011-06-13
  • 2015-11-19
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
相关资源
最近更新 更多