Why is my params hash nil?
Asked Answered
H

2

6

In my rails controller, in a pry session, my params hash is nil. request.params has the expected hash.

If I comment out the params = … line, params returns to normal.

class UsersController < Clearance::UsersController
  skip_before_filter :verify_authenticity_token

  def update
    binding.pry
    params = params.require(:user).allow(:foo)
  end
end

What could be causing this?

Heterogony answered 7/9, 2016 at 23:21 Comment(0)
A
9

To begin with, params is a method. http://api.rubyonrails.org/classes/ActionController/StrongParameters.html#method-i-params

In your code, when you write

params = params.require(:user).allow(:foo)

you initialize a variable called params.

When you hit your pry, you have already initialized (gets initialized upon loading of code) but not yet set the value of your variable, params. Therefore, when you call it within your pry, it is set to nil. The method params is overwritten by your variable within the scope of your update method.

Alumroot answered 2/4, 2018 at 20:0 Comment(0)
T
0

The params hash is what you get when the user request the page. For example:

https://www.example.com/index.html?username=john&[email protected]

The params hash would be

{username: 'john', email: '[email protected]'}

And you can assess then like params[:username].

Looks like you are trying to use strong parameters to set what the user can or cannot update. In that case, what you should do is

def update
  user = User.find(params[:id])
  user.update_attributes(params.require(:user).permit(:foo))
end

This will only allow the user to update the foo attribute and nothing else.

Because this is so common, it is standard to write a private method called user_params and just call that method when you call save.

def update
  user = User.find(params[:id])
  user.update_attributes(user_params)
end

private
  def user_params
    params.require(:user).permit(:foo)
  end
Theran answered 7/9, 2016 at 23:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.