@cschroedによる回答は、最新のRails(v4.2)では機能しませんでした。 Railsのソースコードを掘り下げると、read_attribute
のように見えます 渡されたキーが「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
以来、[]メソッドはread_attribute
を使用します 、これは機能しなくなりました。
代わりに、属性ハッシュから直接読み取ることが機能することがわかりました:
# LegacyModel class
def other_id
@attributes.fetch_value('id')
end
これにより、read_attribute
をバイパスする手段が提供されました。 _read_attribute
を模倣する 。