Does ActiveModel have a module that includes an "update_attributes" method?
Asked Answered
C

2

7

I've set up an ActiveModel class in my Rails app like this:

class MyThingy
   extend ActiveModel::Naming
   extend ActiveModel::Translation
   include ActiveModel::Validations
   include ActiveModel::Conversion

   attr_accessor :username, :favorite_color, :stuff

   def initialize(params)
     #Set up stuff
   end

end

I really want to be able to do this:

thingy = MyThingy.new(params)
thingy.update_attributes(:favorite_color => :red, :stuff => 'other stuff')

I could just write update_attributes on my own, but I have a feeling it exists somewhere. Does it?

Coulomb answered 11/6, 2012 at 6:32 Comment(0)
E
7

No, but there's common pattern for this case:

class Customer
  include ActiveModel::MassAssignmentSecurity

  attr_accessor :name, :credit_rating

  attr_accessible :name
  attr_accessible :name, :credit_rating, :as => :admin

  def assign_attributes(values, options = {})
    sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
      send("#{k}=", v)
    end
  end
end

It's from here. See the link for examples.

If you find yourself repeating this approach often, you can extract this method into a separate module and include include it on demand.

Exam answered 11/6, 2012 at 7:3 Comment(1)
Are there any enlightenings for newer rails versions yet?Sadiras
V
0

It looks like they pulled it out of active record and moved it to active model in Rails 5.

http://api.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html#method-i-assign_attributes

You should be able to include the module:

include ActiveModel::AttributeAssignment
Vizzone answered 30/9, 2016 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.