默认值:Rails资源路由的排除选项
一个小问题:
我正在使用Rails作为我的REST API,但由于它是一个RESTful API我不需要:new
或:edit
我的任何资源的路由,因为人们只会通过自动JSON请求完全与这个API交互,而不是图形化。 例如,不需要专用的编辑页面。
目前,我需要为每个定义的资源执行类似的操作:
# routes.rb resources :people, except: [:new, :edit]
:except
/config/routes.rb
每个资源上的选项:except
它没有什么大不了的,但有没有办法定义默认值,所以我不必在每个资源上都指定这个? 我想稍微干掉这段代码,不要做任何蹩脚的事情,比如在任何地方传递默认选项的局部变量。
更一般地说,您可以设置Rails路由的默认选项,除了:exclude
?
谢谢!
with_options进行救援!
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
之前的文件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
方法。
我会实现CanCan gem。
您可以简化对单个文件的资源访问
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
- 复杂的graphviz树结构
- 如何调用所有评论的post(在这种情况下为锻炼),其中exercise.user_id == current_user.id?
- ConnectionNotEstablished之后在JRuby中有一个multithreading环境
- 使用Nokogiri从空标签中递归清理XML文档?
- Ruby on Rails – 导入CSV文件
- Rails – 带“点”的参数(例如/google.com)
- IRB历史不适用于Ruby 2.3.0
- RVM:如何使用来自不同ruby的gem?
- 在OSX Mountain Lion上安装新的RVM Ruby 1.9.3时出现“错误的ecpoint”SSL错误