I’m new to Ruby, and for the most part it’s starting to make sense, but then I came across this problem.
I searched for a user using:
user = User.find_by_id(user_id)
I can do user.inspect and it displays as:
#<User id: 1, username: "test_user", first_name: "test", last_name: "user">
However, when I try to do:
user[:id]
I get:
undefined method `[]' for nil:NilClass
What am I overlooking?
Here is the user.rb:
class User < ActiveRecord::Base
# Validations
validates :first_name, :last_name, :presence => true
validates :username, :uniqueness => {:allow_blank => true}
# Setup accessible (or protected) attributes for your model
default_fields = [:username, :first_name, :last_name]
attr_accessible *default_fields
# Instance Methods
def full_name
"#{first_name} #{last_name}"
end
end
Additionally, if I do:
user.to_s
it results in:
#<User:0x007fdad09717f8>
Which further leads me to believe that it’s not nil, but yet I can’t reference the hash values.
your first sentence
returned a null object, so you need to test this in order to avoid the exception: