【发布时间】:2014-06-18 12:59:06
【问题描述】:
一个简单的问题,我有点惊讶于 Rails 没有更好地处理这个问题。
我正在尝试使用except!() 方法从许多Rails API 控制器中清除params 中的一些多余属性,如下所示:
params.except!( :format, :api_key, :controller, :action, :updated_at, :created_at )
因为这些属性在许多 API 端点中都是相同的,所以我想将它们存储在 API 的 BaseController 中的 Constant 中,如下所示:
在 BaseController.rb 中
PARAMS_TO_SCRUB = [ :format, :api_key, :controller, :action, :updated_at, :created_at ]
params.except!( PARAMS_TO_SCRUB ) # => Doesn't work.
但except!() 方法只接受一串键,因此没有任何属性被过滤:
# File activesupport/lib/active_support/core_ext/hash/except.rb, line 11
def except!(*keys)
keys.each { |key| delete(key) }
self
end
我现在设置的解决方法是在 BaseController 中创建一个方法,改为使用键擦洗 params,如下所示:
def scrub_params
params.except!( :format, :api_key, :controller, :action, :updated_at, :created_at )
end
有没有办法存储这样的符号列表?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 constants symbols