一个小问题:
我将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