Pregunta

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)?

¿Fue útil?

Solución

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.

Otros consejos

That's an interesting question. I am not sure, but my gut reaction in this situation would simply be to test it out. Whether it breaks or not, you'll have your answer.

I have a User model with an expiration date parameter that I would like only administrators to be able to set. There is no way to incrementally add parameters to the permit list...so you have to break DRY and do it like this...

if can? :manage, :all
   params.require(:user).permit(:first_name, :last_name, :email, :expiration_date)
else
   params.require(:user).permit(:first_name, :last_name, :email)
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top