Pergunta

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.

Foi útil?

Solução

Usually if I want to map params in this way (usually due to some external API) I use the alias_attribute method in ActiveRecord

So if I have params that come to me as {name: "bob", alias_id: 1234} and ideally I would want to have {name: "bob", foreign_id: 1234}

I declare the following in my ActiveRecord model

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

Now my model will always recognise alias_id as mapping to foreign_id in any context and I can push in params.require(:name, :alias_id) and my model will recognise it and process it as required without looping over attributes in my controller.

This is also simpler if you want to do it on other models as well.

Outras dicas

I got the functionality I wanted with the following piece of code. I don't think Strong Parameters can do what I need, especially as require() cannot take multiple parameters.

By putting this in my ApplicationController or a module it inherits

#
# 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

I can now say

Model.create filter_params(:name, {foreign_id: :alias_id})
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top