跳至内容 跳至搜索

Active Model 转换

处理默认转换:to_modelto_keyto_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"
方法
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()

如果任何属性已设置,则返回所有键属性的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]
# 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