Active Model Attributes¶ ↑
Attributes 模块允许模型定义除简单的 Ruby 读写方法之外的属性。与通常从数据库模式推断的 Active Record 属性类似,Active Model Attributes 了解数据类型,可以设置默认值,并可以处理类型转换和序列化。
要使用 Attributes,请在模型类中包含该模块,并使用 attribute 宏定义您的属性。它接受一个名称、一个类型、一个默认值以及属性类型支持的任何其他选项。
示例¶ ↑
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
命名空间
方法
包含的模块
实例公共方法
attribute_names() 链接
返回一个包含属性名称的字符串数组。
class Person include ActiveModel::Attributes attribute :name, :string attribute :age, :integer end person = Person.new person.attribute_names # => ["name", "age"]
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 146 def attribute_names @attributes.keys end
attributes() 链接
返回一个哈希,其中包含所有属性,以属性名称作为键,以属性值作为值。
class Person include ActiveModel::Attributes attribute :name, :string attribute :age, :integer end person = Person.new person.name = "Francesco" person.age = 22 person.attributes # => { "name" => "Francesco", "age" => 22}
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 131 def attributes @attributes.to_hash end