attributes=
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (25)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (-2)
- 3.1.0 (-11)
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
attributes=(new_attributes, guard_protected_attributes = true)
public
Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).
If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
class User < ActiveRecord::Base attr_protected :is_admin end user = User.new user.attributes = { :username => 'Phusion', :is_admin => true } user.username # => "Phusion" user.is_admin? # => false user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false) user.is_admin? # => true
Update attributes on mulitple models
Updates attributes on multiple models, saves each if validations pass.
def update_multiple
@items = Item.find(params[:item_ids]) @items.each do |item| item.attributes = params[:item].reject { |k,v| v.blank? } end if @items.all?(&:valid?) @items.each(&:save!) flash[:notice] = "Updated items!" redirect_to items_path else flash[:notice] = "Please enter valid data." render :action => 'edit_multiple' end end
Use super to override, and not alias_method_chain
Somehow, If you want to extend the behaviour of attributes=,
alias_method_chain does not work. It simply breaks (could not find out how exactly).
def attributes_with_some_feature=(new_attributes, guard_protected_attributes = true) attributes_without_some_feature=(new_attributes, guard_protected_attributes) end alias_method_chain :attributes=, :some_feature
this breaks the code. dynamic finders and assignments didn’t work as before (Even though no behaviour has changed yet).
Instead,
def attributes=(new_attributes, guard_protected_attributes = true) # custom code super(new_attributes, guard_protected_attributes) end
does work as expected.
I prefer using alias_method_chain for breaking open existing functionality, but in this case it won’t work.
the source is wrong!
in 3.0.5, the source code in line 15 looks like this:
respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
whats wrong with apidock?