跳至内容 跳至搜索

Active Record 属性方法类型转换前

ActiveRecord::AttributeMethods::BeforeTypeCast 提供了一种在类型转换和反序列化之前读取属性值的方法。

class Task < ActiveRecord::Base
end

task = Task.new(id: '1', completed_on: '2012-10-21')
task.id           # => 1
task.completed_on # => Sun, 21 Oct 2012

task.attributes_before_type_cast
# => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
task.read_attribute_before_type_cast('id')           # => "1"
task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"

除了 read_attribute_before_type_castattributes_before_type_cast,它还为所有属性声明了一个以 *_before_type_cast 结尾的方法。

task.id_before_type_cast           # => "1"
task.completed_on_before_type_cast # => "2012-10-21"
方法
A
R

实例公开方法

attributes_before_type_cast()

返回类型转换和反序列化之前的属性哈希。

class Task < ActiveRecord::Base
end

task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
task.attributes
# => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
task.attributes_before_type_cast
# => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
# File activerecord/lib/active_record/attribute_methods/before_type_cast.rb, line 82
def attributes_before_type_cast
  @attributes.values_before_type_cast
end

attributes_for_database()

返回分配给数据库的属性哈希。

# File activerecord/lib/active_record/attribute_methods/before_type_cast.rb, line 87
def attributes_for_database
  @attributes.values_for_database
end

read_attribute_before_type_cast(attr_name)

返回在类型转换和反序列化之前由 attr_name 标识的属性的值。

class Task < ActiveRecord::Base
end

task = Task.new(id: '1', completed_on: '2012-10-21')
task.read_attribute('id')                            # => 1
task.read_attribute_before_type_cast('id')           # => '1'
task.read_attribute('completed_on')                  # => Sun, 21 Oct 2012
task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
task.read_attribute_before_type_cast(:completed_on)  # => "2012-10-21"
# File activerecord/lib/active_record/attribute_methods/before_type_cast.rb, line 48
def read_attribute_before_type_cast(attr_name)
  name = attr_name.to_s
  name = self.class.attribute_aliases[name] || name

  attribute_before_type_cast(name)
end

read_attribute_for_database(attr_name)

返回序列化后由 attr_name 标识的属性的值。

class Book < ActiveRecord::Base
  enum :status, { draft: 1, published: 2 }
end

book = Book.new(status: "published")
book.read_attribute(:status)              # => "published"
book.read_attribute_for_database(:status) # => 2
# File activerecord/lib/active_record/attribute_methods/before_type_cast.rb, line 65
def read_attribute_for_database(attr_name)
  name = attr_name.to_s
  name = self.class.attribute_aliases[name] || name

  attribute_for_database(name)
end