Method: ActiveModel::MassAssignmentSecurity::ClassMethods#attr_accessible
- Defined in:
- lib/active_model/mass_assignment_security.rb
#attr_accessible(*names) ⇒ Object
Specifies a white list of model attributes that can be set via mass-assignment.
This is the opposite of the attr_protected macro: Mass-assignment will only set attributes in this list, to assign to the rest of attributes you can use direct writer methods. This is meant to protect sensitive attributes from being overwritten by malicious users tampering with URLs or forms. If you’d rather start from an all-open default and restrict attributes as needed, have a look at attr_protected.
class Customer
include ActiveModel::MassAssignmentSecurity
attr_accessor :name, :credit_rating
attr_accessible :name
def attributes=(values)
sanitize_for_mass_assignment(values).each do |k, v|
send("#{k}=", v)
end
end
end
customer = Customer.new
customer.attributes = { :name => "David", :credit_rating => "Excellent" }
customer.name # => "David"
customer. # => nil
customer. = "Average"
customer. # => "Average"
Note that using Hash#except or Hash#slice in place of attr_accessible to sanitize attributes won’t provide sufficient protection.
126 127 128 129 |
# File 'lib/active_model/mass_assignment_security.rb', line 126 def attr_accessible(*names) self._accessible_attributes = self.accessible_attributes + names self. = self._accessible_attributes end |