方法
執行個體公共方法
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=
來源: 顯示 | 在 GitHub 上
# 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'"
來源: 顯示 | 在 GitHub 上
# File activemodel/lib/active_model/attribute_assignment.rb, line 56 def attribute_writer_missing(name, value) raise UnknownAttributeError.new(self, name) end