跳至内容 跳至搜索

Active Model 转换

处理默认转换:to_modelto_keyto_paramto_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"
方法
P
T

类公共方法

param_delimiter

接受一个字符串,该字符串将在 `to_param` 方法中用作对象键值的定界符。

# 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]
# 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 兼容的方法包装你的对象。

# 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"
# 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"
# File activemodel/lib/active_model/conversion.rb, line 103
def to_partial_path
  self.class._to_partial_path
end