Default value: exclude for routing Rails resources.
Small question:
I am using Rails for my REST API, but since this is a RESTful API, I don't really need routes :new
or :edit
for any of my resources, as people will interact with this API entirely through automatic JSON requests, not graphically. For example, there is no need for a dedicated edit page.
Currently I need to do something like this for every specific resource:
# routes.rb
resources :people, except: [:new, :edit]
It's not important to have options :except
for each resource in /config/routes.rb
, but is there a way to define defaults so I don't need to specify this on every resource? I would like to GET this code a little without doing something lame, how would I bypass the local variable with all the default parameters.
More generally, can you set default parameters for Rails routes to follow :exclude
?
Thank!
source to share
with_options to the rescue!
with_options(except: [:new, :edit]) do |opt|
opt.resource :session
opt.resource :another_resource
opt.resources :people
end
source to share
You can define a custom method for drawing routes in the namespace ActionDispatch::Routing::Mapper
. In your file routes.rb
, on top of the file before Rails.application.routes.draw do
:
class ActionDispatch::Routing::Mapper
def draw(resource)
resources resource, except: [:new, :edit]
end
end
#routes start here
Rails.application.routes.draw do
draw :people
draw :products
# ...rest of the routes
end
Now, for these specific resources, you can call the method draw
as above.
source to share
I would use the CanCan gem.
You can simplify access to resources in one file
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
Then in your controller you can enforce the resources with a single line
class CustomersController < ApplicationController
load_and_authorize_resource
...
end
Defining Abilities https://github.com/ryanb/cancan/wiki/Defining-Abilities
Controller level authorization https://github.com/ryanb/cancan/wiki/authorizing-controller-actions
source to share