BUILDING A SOCIAL NETWORKING
WEBSITE WITH RUBY ON RAILS

Tracking down a gsub bug

Posted over 2 years ago by Michael Hartl

There’s a discussion on the RailsSpace Google group about a problem some people are having with the user authorization token identifying each logged-in user in the session. The offending code is on p. 199, Listing 7.10:

user.authorization_token = user.id 
user.save! 
cookies[:authorization_token] = {
    :value   => user.authorization_token,
    :expires => 10.years.from_now }

This code works on all the systems we tested, but some people get an error from the line setting the cookie value to the user authorization token:

:value   => user.authorization_token

gives the error

NoMethodError in UserController#login
private method `gsub' called for 1:Fixnum

What’s going on here? By searching online or looking in the Pickaxe, you can discover that gsub is a String method, which does a global substitution of one string for another. The error is telling us that somewhere in the cookie machinery gsub is getting called on the user id, which is of class Fixnum, not String.

We’re not sure why this error shows up in Rails, but it’s not all that surprising, since Rails comes in many slightly different versions and has many external dependencies. (There is a Rails bug ticket that gives a hint of what the problem could be.) In any case, if you get this error in your development environment, the solution is simple: convert the user authorization token from Fixnum to String using the to_s method:

user.authorization_token = user.id 
user.save! 
cookies[:authorization_token] = {
    :value   => user.authorization_token.to_s,
    :expires => 10.years.from_now }

We should note that this problem exists only for the example shown, which is highly insecure and is included in the book only for purposes of illustration. As those following the book know, in short order we switch to a much more secure solution using the Digest::SHA1.hexdigest hashing algorithm.

Comments

There are 2 comments on this post.

beaupre
posted about 1 year ago

NoMethodError: undefined method “authorization_token=” for #<User…

I’m getting this error when I test the testloginsuccesswithremember_me.

Any idea what might be causing it?
I’m running ruby on windows (stop groaning)

Even though I’ve tried to hack through and even tried copying the exact text for user.controller and user.controller.test from the site, I still can’t resolve the error.

Please help.

Thanks


posted about 1 year ago

Hi. I’m also getting the error posted above

(NoMethodError: undefined method “authorization_token=” for #<User…

Can’t find an explanation of this anywhere. Thanks.