Rails params.nil? if else

1.6k Views Asked by At

I have this simple rails code and something weird is happening. As you can see params.nil? is true and it's still calling the else part. What am I missing here?

Pry Session

     5: def build_resource
     6:   binding.pry
     7:   if params.nil?
     8:     model_class.new
     9:   else
 => 10:     params = params.merge(dealer: {})
    11:     model_class.new(dealer_params)
    12:   end
    13: end

[3] pry(#<Admin::DealersController>):1> params.nil?
true
2

There are 2 best solutions below

0
On

So, this answer my question (https://stackoverflow.com/a/1335890):

The params which contains the request parameters is actually a method call which returns a hash containing the parameters. Your params = line is assigning to a local variable called params.

After the if false block, Ruby has seen the local params variable so when you refer to params later in the method the local variable has precedence over calling the method of the same name. However because your params = assignment is within an if false block the local variable is never assigned a value so the local variable is nil.

If you attempt to refer to a local variable before assigning to it you will get a NameError:

irb(main):001:0> baz
NameError: undefined local variable or method `baz' for main:Object
        from (irb):1

However if there is an assignment to the variable which isn't in the code execution path then Ruby has created the local variable but its value is nil.

irb(main):007:0> baz = "Example" if false
=> nil
irb(main):008:0> baz
=> nil
4
On

No, Its not a pry issue. You just cant reassign params to params. Try using different variable. This should work fine.

You can use as

dealer_params = params.merge(dealer: {})

updated answer

Digging Deeper inside Rails. Have a look at this.

class Parameters

cattr_accessor :permit_all_parameters, instance_accessor: false, default: false

cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false

.....
end

Simple Explanation: params are responsible for carrying value which you permit inside your controller, but its resigning it will return false or nil. You can study about these topics in dept you get to know.

https://apidock.com/rails/Class/cattr_accessor

That's why when you declare new variable the value of params => (object) is assigns to it. But when you do the same thing with params or method that return an object this will give nil.

SAME Answer: you just can't reassign params to params.