默认值:排除Rails资源路由选项



一个小问题:

我将Rails用于我的REST API,但由于它是一个RESTful API,所以我的任何资源都不需要:new:edit路由,因为人们只会完全通过自动的JSON请求与这个API交互,而不是以图形方式交互。例如,不需要专门的编辑页面。

目前,我需要为每个定义的资源做这样的事情:

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

/config/routes.rb中的每个资源上都有:except选项并不是什么大不了的事,但有没有一种方法可以定义默认值,这样我就不必在每个资源上指定它了?我想把这段代码弄干一点,不要做一些蹩脚的事情,比如到处传递一个带有默认选项的局部变量。

更一般地说,除了:exclude之外,您能为Rails路由设置默认选项吗?

谢谢!

具有救援选项!

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

您可以定义一个自定义方法来在ActionDispatch::Routing::Mapper命名空间下绘制路线。在routes.rb文件中,在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

现在,对于那些特定的资源,您可以如上所述调用draw方法。

我将实现CanCangem。

您可以简化对单个文件的资源访问

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

然后在您的控制器中,您可以使用单行强制执行资源

class CustomersController < ApplicationController
    load_and_authorize_resource
    ...
end

定义能力https://github.com/ryanb/cancan/wiki/Defining-Abilities

控制器级别的授权https://github.com/ryanb/cancan/wiki/authorizing-controller-actions