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"
來源: 顯示 | 在 GitHub 上
# 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
來源: 顯示 | 在 GitHub 上
# File activemodel/lib/active_model/api.rb, line 95 def persisted? false end