【问题标题】:api resource rails routesapi 资源 rails 路线
【发布时间】:2017-01-03 15:20:49
【问题描述】:
所以我的应用中有一些 API 资源,还有一些常规资源,对于常规资源,我使用:
resources :books
然后我可以通过except: %i(destroy new edit) 或only,效果很好!但是对于我的资源,我永远不会有新的/编辑操作,有时我还需要传递 except 和 only 选项。
我正在考虑创建类似的东西:
api_resources:书籍
默认情况下没有新/编辑操作,我该怎么做?
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-4
【解决方案1】:
也许是这样的?
# config/routes.rb
Rails.application.routes.draw do
def api_resources(res)
resources res, only: [:new, :edit]
end
api_resources :a
api_resources :b
end
# output
Prefix Verb URI Pattern Controller#Action
new_a GET /a/new(.:format) a#new
edit_a GET /a/:id/edit(.:format) a#edit
new_b GET /b/new(.:format) b#new
edit_b GET /b/:id/edit(.:format) b#edit
【解决方案2】:
@Amree 的回答无法处理嵌套资源。一个改进是:
# config/routes.rb
Rails.application.routes.draw do
def editable_resoustrong textrces(res, &block)
resources res, only: %i[new edit], &block
end
editable_resources :a
end
# output
Prefix Verb URI Pattern Controller#Action
new_a GET /a/new(.:format) a#new
edit_a GET /a/:id/edit(.:format) a#edit