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") end end
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 end
I get valid attributes ie.
--- !ruby/object:User attributes: id: 1 email: firstname.lastname@example.org 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('email@example.com') User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`email` = 'firstname.lastname@example.org' LIMIT 1 => #<User id: 1, email: "email@example.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") end
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.