Active Model Conversion
處理預設轉換:to_model
、to_key
、to_param
和 to_partial_path
。
我們以這個非持續性物件為例。
class ContactMessage
include ActiveModel::Conversion
# ContactMessage are never persisted in the DB
def persisted?
false
end
end
cm = ContactMessage.new
cm.to_model == cm # => true
cm.to_key # => nil
cm.to_param # => nil
cm.to_partial_path # => "contact_messages/contact_message"
方法
類別公開方法
param_delimiter 連結
接受一個字串,該字串會用在物件金鑰值在`to_param`方法中的分隔號。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/conversion.rb, line 32 class_attribute :param_delimiter, instance_reader: false, default: "-"
實例公開方法
to_key() 連結
回傳所有金鑰屬性的陣列
,如果任何一個屬性已被設定,不論物件是否持續。如果沒有任何金鑰屬性,則回傳nil
。
class Person
include ActiveModel::Conversion
attr_accessor :id
def initialize(id)
@id = id
end
end
person = Person.new(1)
person.to_key # => [1]
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/conversion.rb, line 67 def to_key key = respond_to?(:id) && id key ? Array(key) : nil end
to_model() 連結
如果你的物件已設計為實作所有的 Active Model,你可以使用預設的:to_model
實作方式,這會簡單地回傳self
。
class Person
include ActiveModel::Conversion
end
person = Person.new
person.to_model == person # => true
如果你的模型不像是 Active Model 物件,那麼你應該自己定義:to_model
,回傳一個代理物件,將你的物件封裝在符合 Active Model 的方法中。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/conversion.rb, line 49 def to_model self end
to_param() 連結
回傳字串,表示物件金鑰,適合在 URL 中使用,或者如果 persisted?
是 false
,則回傳nil
。
class Person
include ActiveModel::Conversion
attr_accessor :id
def initialize(id)
@id = id
end
def persisted?
true
end
end
person = Person.new(1)
person.to_param # => "1"
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/conversion.rb, line 90 def to_param (persisted? && (key = to_key) && key.all?) ? key.join(self.class.param_delimiter) : nil end
to_partial_path() 連結
回傳一個識別與該物件相關聯的路徑的字串
。ActionPack 使用它來找到一個合適的部分來表示該物件。
class Person
include ActiveModel::Conversion
end
person = Person.new
person.to_partial_path # => "people/person"
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/conversion.rb, line 103 def to_partial_path self.class._to_partial_path end