跳至内容 跳至搜索

Active Record 属性方法读取

方法
R

实例公共方法

read_attribute(attr_name, &block)

在类型转换后,返回由 attr_name 标识的属性值。例如,日期属性将把“2004-12-12”转换为 Date.new(2004, 12, 12)。(有关特定类型转换行为的信息,请参阅 ActiveModel::Type 下的类型。)

# File activerecord/lib/active_record/attribute_methods/read.rb, line 29
      def read_attribute(attr_name, &block)
        name = attr_name.to_s
        name = self.class.attribute_aliases[name] || name

        return @attributes.fetch_value(name, &block) unless name == "id" && @primary_key

        if self.class.composite_primary_key?
          @attributes.fetch_value("id", &block)
        else
          if @primary_key != "id"
            ActiveRecord.deprecator.warn(<<-MSG.squish)
              Using read_attribute(:id) to read the primary key value is deprecated.
              Use #id instead.
            MSG
          end
          @attributes.fetch_value(@primary_key, &block)
        end
      end