跳至内容 跳至搜索
方法
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)

别名为:assign_attributes