Erik
Erik

Reputation: 1254

Rails: editing the params hash

I am trying to figure out how to edit the params hash in the controller after it's been passed. My hash is set up like this:

 def user_params
    params.require(:user).permit(:username, :password, :password_confirmation, :user_type_id)
 end

I have this method for editing the hash

def alter_user_params_when_not_admin(user_params)
   if(@logged_in_user)
     if(!@logged_in_user.is_admin)
       user_params[:user][:user_type_id] = 1
     end
   else
     user_params[:user][:user_type_id]=1
   end
   user_params
 end

I call this method like this:

def update
   new_user_params = alter_user_params_when_not_admin(user_params)
   respond_to do |format|
      if @user.update(new_user_params)

But on the fourth line of the alter_user_params... method I get this error:

undefined method `[]=' for nil:NilClass 

Upvotes: 0

Views: 123

Answers (2)

Zakwan
Zakwan

Reputation: 1072

user_params gives you same what params[:user] gives but with strong parameters filtration. So, when you use user_params, you don't need to pass [:user], just call user_params[:user_type_id] directly.

I suggest the following code:

def alter_user_params_when_not_admin(user_params)
  if(@logged_in_user)
    if(!@logged_in_user.is_admin)
      params[:user][:user_type_id] = 1
    end
  else
    params[:user][:user_type_id] = 1
  end

  user_params
end

UPDATE:

We don't need to pass and return user_params in your custom method:

def alter_user_params_when_not_admin
  if(@logged_in_user)
    if(!@logged_in_user.is_admin)
      params[:user][:user_type_id] = 1
    end
  else
    params[:user][:user_type_id] = 1
  end
end

And:

def update
  alter_user_params_when_not_admin
  respond_to do |format|
    if @user.update(user_params)

Upvotes: 1

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34328

The reason of that error is:

`user_params[:user]` is `nil` there!

permit returns a new hash with the keys in it, so you have to save a reference to the hash that user_params returns and then modify that.

This should work:

def alter_user_params_when_not_admin(user_params)
   #getting the current user_params in another hash
   modified_user_params = user_params

   if(@logged_in_user)
     if(!@logged_in_user.is_admin) 
       #modify the hash      
       modified_user_params[:user_type_id] = 1
     end
   else
     #modify the hash
     modified_user_params[:user_type_id] = 1
   end
   #return the modified user_params hash
   modified_user_params
end

Upvotes: 0

Related Questions