跳至內容 跳至搜尋

ActiveRecord 屬性方法變換型態前

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