Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

391
Views
What's the difference between using belongs_to.attribute and belongs_to[:attribute] in a model?

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
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!