跳到内容 跳到搜索

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