跳至内容 跳至搜索
方法
A
T

实例公共方法

attribute(name, cast_type = nil, default: nil, **options)

定义一个模型属性。除了属性名称,还可以指定转换类型和默认值,以及给定转换类型支持的任何选项。

class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :active, :boolean, default: true
end

person = Person.new
person.name = "Volmer"

person.name   # => "Volmer"
person.active # => true
# File activemodel/lib/active_model/attributes.rb, line 59
def attribute(name, ...)
  super
  define_attribute_method(name)
end

attribute_names()

返回一个字符串形式的属性名称数组。

class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :age, :integer
end

Person.attribute_names # => ["name", "age"]
# File activemodel/lib/active_model/attributes.rb, line 74
def attribute_names
  attribute_types.keys
end

type_for_attribute(attribute_name, &block)

返回指定属性应用任何修饰符后的类型。此方法是有关模型属性类型信息的唯一有效来源。此方法的返回值将实现 ActiveModel::Type::Value 描述的接口(尽管对象本身可能不继承自它)。

# File activemodel/lib/active_model/attributes.rb, line 79