Rails Model Attribute

Going a little crazy here. I am doing a very simple lookup of a user by its email and then if I have a user checking its role. quick example.

user = User.find_by_email(params[:email])
if user
  if user.role == 'admin'
    abort("Yay were an admin")

The user has a role like in the example but the if statement is not returning true.

If I inspect the user ie,

if user
  raise user.to_yaml

I get valid attributes ie.

--- !ruby/object:User
  id: 1
  email: user@test.com
  created_at: 2011-12-01 08:37:45.000000000Z
  updated_at: 2011-12-01 08:37:45.000000000Z
  role: admin

Why would the if statement not return true? I know the user has a roel as if I do if user.role it returns true.

Doing the same in rails console gives me the user role.

ruby-1.9.2-p180 :001 > u = User.find_by_email('user@test.com')
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`email` = 'user@test.com' LIMIT 1
 => #<User id: 1, email: "user@test.com", created_at: "2011-12-01 08:37:45", updated_at: "2011-12-01 08:37:45", role: "admin"> 
ruby-1.9.2-p180 :002 >

But then trying a if statement fails as well

ruby-1.9.2-p180 :008 > if u.role == 'admin'
ruby-1.9.2-p180 :009?>   puts 'Yay'
ruby-1.9.2-p180 :010?>   end
 => nil 
ruby-1.9.2-p180 :011 > 

Any ideas ??


According to your comments, the user's role attribute returns a symbol. Therefore, your test should be

if user.role == :admin
  abort("Yay were an admin")

Possibly the column name role is reserved, depending on what database you are using, which can cause all kinds of strange conflicts.

I had the same problem with my first Rails project using a column called error in sqlite3 - try renaming the role column to project_role or similar and see if that helps.

There was a great resource for checking reserved names at yup.com which has since gone down, here is the only mirror I can find.

Need Your Help

what should I do if I got a null pointer?

c++ pointers exception-handling

The main thing is I don't know the best practice of handling null pointers.

How to remove an object from List<T> in C# and return the removed object?

c# .net list

How to remove an object from List&lt;T&gt; in C# and return the removed object ?