2014-10-28 41 views
3

A小調問題:默認:排除Rails的資源路由選項

我使用我的REST API的Rails,但因爲它是一個RESTful API我並不真的需要:new:edit路線我的任何資源因爲人們只會通過自動JSON請求完全與此API進行交互,而不是以圖形方式。例如,不需要專門的編輯頁面。

目前,我需要爲定義的每個資源做這樣的事情:

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

這不是什麼大不了的有在/config/routes.rb的每一個資源:except選項,但有一種方式來定義默認值,所以我不必在每個資源上指定它?我想幹掉這段代碼,而不是像在任何地方使用默認選項一樣傳遞一個局部變量。

更一般地說,你可以設置Rails路由的默認選項,以便從:exclude開始按照預設選項進行操作嗎?

謝謝!

回答

7

with_options救援!

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

漂亮!謝謝! – 2014-10-29 20:16:41

1

您可以定義一個自定義方法來在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方法。

0

我會執行CanCan寶石。

可以簡化爲一個單一的文件

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