跳至内容 跳至搜索

Active Model API

包含对象与 Action Pack 和 Action View 交互所需的接口,这些接口使用了不同的 Active Model 模块。它包含了模型的名称自省、转换、翻译和验证。此外,它允许你使用属性的哈希值来初始化对象,这与 Active Record 的方式非常相似。

一个最小化的实现可以是

class Person
  include ActiveModel::API
  attr_accessor :name, :age
end

person = Person.new(name: 'bob', age: '18')
person.name # => "bob"
person.age  # => "18"

请注意,默认情况下,ActiveModel::API 实现的 persisted? 方法返回 false,这是最常见的情况。你可能希望在你的类中重写它来模拟不同的场景。

class Person
  include ActiveModel::API
  attr_accessor :id, :name

  def persisted?
    self.id.present?
  end
end

person = Person.new(id: 1, name: 'bob')
person.persisted? # => true

另外,如果你出于某种原因需要在初始化时(::new)运行代码,请确保在调用 super 时,你希望进行属性哈希值的初始化。

class Person
  include ActiveModel::API
  attr_accessor :id, :name, :omg

  def initialize(attributes={})
    super
    @omg ||= true
  end
end

person = Person.new(id: 1, name: 'bob')
person.omg # => true

有关其他可用功能的详细信息,请参阅 ActiveModel::API 中包含的特定模块(见下文)。

方法
N
P
包含的模块

类公共方法

new(attributes = {})

使用给定的 params 初始化新模型。

class Person
  include ActiveModel::API
  attr_accessor :name, :age
end

person = Person.new(name: 'bob', age: '18')
person.name # => "bob"
person.age  # => "18"
# File activemodel/lib/active_model/api.rb, line 80
def initialize(attributes = {})
  assign_attributes(attributes) if attributes

  super()
end

实例公共方法

persisted?()

指示模型是否已持久化。默认为 false

class Person
  include ActiveModel::API
  attr_accessor :id, :name
end

person = Person.new(id: 1, name: 'bob')
person.persisted? # => false
# File activemodel/lib/active_model/api.rb, line 95
def persisted?
  false
end