Default :exclude option for Rails resource routing

2019-04-10 08:42发布

问题:

A minor question:

I am using Rails for my REST API, but since it is a RESTful API I don't really need :new or :edit routes for any of my resources since people will only be interacting with this API entirely through automated JSON requests, not graphically. There's no need for a dedicated edit page, for instance.

Currently, I need to do something like this for every resource defined:

# routes.rb
resources :people, except: [:new, :edit]

It's not a big deal to have :except options on every resource in /config/routes.rb, but is there a way to define defaults so I don't have to specify this on every resource? I'd like to DRY up this code a bit, without doing something lame like passing around a local variable with default options everywhere.

More generally, can you set default options for Rails routes to follow aside from :exclude?

Thanks!

回答1:

with_options for a rescue!

with_options(except: [:new, :edit]) do |opt|
  opt.resource :session
  opt.resource :another_resource
  opt.resources :people
end


回答2:

You can define a custom method to draw your routes under ActionDispatch::Routing::Mapper namespace. In your routes.rb file, 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 those particular resources you can call the draw method as above.



回答3:

I would implement the CanCan gem.

You can simplify access to resources to a single 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 have 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

Authorizing at Controller level https://github.com/ryanb/cancan/wiki/authorizing-controller-actions