Active Model 基础模型¶ ↑
允许实现类似于 ActiveRecord::Base 的模型。包含 ActiveModel::API,提供了对象与 Action Pack 和 Action View 交互所需的接口,但也可以通过其他功能进行扩展。
一个最小化的实现可以是
class Person include ActiveModel::Model attr_accessor :name, :age end person = Person.new(name: 'bob', age: '18') person.name # => "bob" person.age # => "18"
如果您出于某种原因需要在 initialize 时运行代码,请确保调用 super,以便进行属性哈希初始化。
class Person include ActiveModel::Model attr_accessor :id, :name, :omg def initialize(attributes={}) super @omg ||= true end end person = Person.new(id: 1, name: 'bob') person.omg # => true
有关其他可用功能的详细信息,请参阅 ActiveModel::Model 中包含的特定模块(如下文所示)。
方法
包含的模块
实例公共方法
slice(*methods) 链接
返回一个包含给定方法的哈希,其键为方法名,值为返回的属性值。
person = Person.new(id: 1, name: "bob") person.slice(:id, :name) # => { "id" => 1, "name" => "bob" }
来源: 在 GitHub 上
# File activemodel/lib/active_model/model.rb, line 48
values_at(*methods) 链接
返回一个数组,包含由给定方法返回的值。
person = Person.new(id: 1, name: "bob") person.values_at(:id, :name) # => [1, "bob"]
来源: 在 GitHub 上
# File activemodel/lib/active_model/model.rb, line 63