Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

397
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda