开发者

Params becomming nil

Had some old code that on some condition would modify params. I believe it was working before (not 100%). We are now getting params set to nil whether or not the condition is met.

The culprit is within the condition, I perform a params = tmp.dup. Even when the conditio开发者_运维技巧n is false, this is causing an error in the update action.

I was able to recreate with a minimal test

(Rails 2.3.5)

rails bug;
cd bug;

script/generate scaffold bug name:string;
rake db:create;
rake db:migrate;

edit apps/controllers/bugs_controller.rb add to beginning of update action

l_p = params.dup

if (false)

  params = l_p.dup  # NOT REACHED

end

script/server WEBrick -p 5001

browse to http://localhost:5001/bugs create a new bug edit bug submit


Per user45147 comment, the correct answer for this question is here:

assign/replace params hash in rails

Copying here:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜