Is there a chance that the methods below will yield different values, like because of cache or anything?
class User < ActiveRecord::Base
belongs_to :school
def first_value
school.name
end
def second_value
school[:name]
end
end
Usually, there is no difference between calling an attribute by its name or by using the [] method because the attribute name getter method uses the [] method internally. And therefore both return the value of that attribute after it has been typecasted.
But there might be a difference between both methods when the attribute getter method is overwritten in your application. Imagine the method was overwritten like this
def name
self[:name].presence || 'N.N.'
end
Then school.name would return the school's if the school has a name but it would return the string 'N.N.' if the name was blank. Whereas school[:name] would still return the original value from the database which means it would still return nil if the school's name hasn't been set.