La respuesta de @cschroed no me funcionó en el último Rails (v4.2). Profundizando en el código fuente de Rails, parece que read_attribute
también usará el valor de la clave principal si la clave pasada es igual a 'id':
ID = 'id'.freeze
# Returns the value of the attribute identified by <tt>attr_name</tt> after
# it has been typecast (for example, "2004-12-12" in a date column is cast
# to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name, &block)
name = attr_name.to_s
name = self.class.primary_key if name == ID
_read_attribute(name, &block)
end
Dado que el método [] usa read_attribute
, esto ya no funciona.
Descubrí que la lectura directa del hash de atributos funcionó en su lugar:
# LegacyModel class
def other_id
@attributes.fetch_value('id')
end
Esto proporcionó un medio para eludir read_attribute
imitando _read_attribute
.