Does anyone know, if with strong_parameters gem, we can incrementally add attributes like below:
def user_params
params[:user].permit(:name, :email)
if current_user.admin?
params[:user].permit(:is_admin)
end
end
Here I am incrementally asking the code to permit :is_admin
parameter if the current user is an admin. Shouldn't it just add to the previously permitted list of parameters (:name
and :email
)?
They way I have done it is to put all my params in a class Like the strong-parameters railscast..
this way I have something like this
class PermittedParams < Struct.new(:params,:admin)
def administrator_attributes
allowed = [:email, :name, :password, :password_confirmation, :password_digest]
if admin.has_any_role? :realm_admin, :system_admin
allowed << :active << :roles
end
allowed
end
.... other models ....
def method_missing(method,*args,&block)
attributes_name = method.to_s + '_attributes'
if respond_to? attributes_name, false
params.require(method).send(:permit, *method(attributes_name).call)
else
super
end
end
end
then in the controller just call @administrator.update_attributes(permitted_params.administrator)
as it is just an array you can build up the array, and then just use * to pass it into the permit.