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 Link
接受一个字符串,该字符串将用作 `to_param` 方法中对象键值的分隔符。
实例公共方法
to_key() Link
如果任何属性已设置,则返回所有键属性的 Array,无论对象是否已持久化。如果没有键属性,则返回 nil。
class Person include ActiveModel::Conversion attr_accessor :id def initialize(id) @id = id end end person = Person.new(1) person.to_key # => [1]
to_model() Link
如果您的对象已设计为实现所有 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 的方法包装您的对象。
to_param() Link
返回一个 string,表示对象适合在 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"
to_partial_path() Link
返回一个 string,标识与对象关联的路径。ActionPack 使用此路径来查找表示对象的合适部分。
class Person include ActiveModel::Conversion end person = Person.new person.to_partial_path # => "people/person"