Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

api resource rails routes

So I have some API resources in my app, and some regular resources, and for regular resources I use :

resources :books

And then I could pass except: %i(destroy new edit) or only so works great! However for my resource I ll never have new/edit actions, sometimes I will need to pass except and only options too.

I was thinking to create something like:

api_resources :books

Which comes without new/edit actions by default, how would I do that?

Upvotes: 1

Views: 1419

Answers (2)

Yang Liu
Yang Liu

Reputation: 173

@Amree's answer can not handle nested resources. An improvement would be:

# 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

Upvotes: 0

Amree
Amree

Reputation: 2890

Maybe something like this?

# 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

Upvotes: 3

Related Questions