7

Lets say I had code in a controller that did not use Strong Parameters

Model.create name: params[:name], alias_id: params[:foreign_id]

Is it possible for me to use Strong Parameters here?

I cannot do

Model.create params.require(:name, :foreign_id)

Because foreign_id is not a param

I cannot do

Model.create params.require(:name, :alias_id)

Because alias_id is not on the model.

Basically, I want to know if you can alias paramater keys when using Strong Parameters.

4

2 回答 2

18

通常,如果我想以这种方式映射参数(通常是由于某些外部 API),我会alias_attribute使用ActiveRecord

所以如果我有参数来找我{name: "bob", alias_id: 1234},理想情况下我会想要{name: "bob", foreign_id: 1234}

我在我的ActiveRecord模型中声明以下内容

class MyModel < ActiveRecord::Base
  alias_attribute :alias_id, :foreign_id
end

现在,我的模型将始终识别alias_idforeign_id在任何上下文中的映射,并且我可以推入params.require(:name, :alias_id),我的模型将识别它并根据需要处理它,而无需循环控制器中的属性。

如果您也想在其他模型上执行此操作,这也更简单。

于 2016-06-22T13:28:44.040 回答
3

我通过以下代码获得了我想要的功能。我不认为强参数可以做我需要的,特别是因为 require() 不能接受多个参数。

通过把它放在我的 ApplicationController 或它继承的模块中

#
# Pass in a list of param keys to pull out of the params object
# Alias param keys to another key by specifiying a mapping with a Hash
# eg.  filter_params :foo, :bar, {:choo => :zoo}
#
def filter_params(*param_list)
  filtered_params = {}
  param_list.each do |param|
    if param.is_a? Hash
      param.each {|key, value| filtered_params[value] = params[key]}
    else
      filtered_params[param] = params[param]
    end
  end
  filtered_params
end

我现在可以说

Model.create filter_params(:name, {foreign_id: :alias_id})
于 2013-03-15T06:56:24.083 回答