跳至内容 跳至搜索
方法
A

实例公共方法

assign_attributes(new_attributes)

允许您通过传递一个属性哈希来设置所有属性,该哈希的键与属性名称匹配。

如果传递的哈希响应于 permitted? 方法,并且该方法的返回值为 false,则会引发一个 ActiveModel::ForbiddenAttributesError 异常。

class Cat
  include ActiveModel::AttributeAssignment
  attr_accessor :name, :status
end

cat = Cat.new
cat.assign_attributes(name: "Gorby", status: "yawning")
cat.name # => 'Gorby'
cat.status # => 'yawning'
cat.assign_attributes(status: "sleeping")
cat.name # => 'Gorby'
cat.status # => 'sleeping'
也称为:attributes=
# File activemodel/lib/active_model/attribute_assignment.rb, line 28
def assign_attributes(new_attributes)
  unless new_attributes.respond_to?(:each_pair)
    raise ArgumentError, "When assigning attributes, you must pass a hash as an argument, #{new_attributes.class} passed."
  end
  return if new_attributes.empty?

  _assign_attributes(sanitize_for_mass_assignment(new_attributes))
end

attribute_writer_missing(name, value)

与 'BasicObject#method_missing' 一样,当 '#assign_attributes' 传递了未知属性名称时,会调用 '#attribute_writer_missing'。

默认情况下,'#attribute_writer_missing' 会引发一个 UnknownAttributeError

class Rectangle
  include ActiveModel::AttributeAssignment

  attr_accessor :length, :width

  def attribute_writer_missing(name, value)
    Rails.logger.warn "Tried to assign to unknown attribute #{name}"
  end
end

rectangle = Rectangle.new
rectangle.assign_attributes(height: 10) # => Logs "Tried to assign to unknown attribute 'height'"
# File activemodel/lib/active_model/attribute_assignment.rb, line 56
def attribute_writer_missing(name, value)
  raise UnknownAttributeError.new(self, name)
end

attributes=(new_attributes)