What's the difference between using belongs_to.attribute and belongs_to[:attribute] in a model?
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.