Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

402
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda