Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 605
Brandon Yarbrough Avatar asked Jun 11 '12 06:06

Brandon Yarbrough


1 Answers

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.

like image 65
jdoe Avatar answered Sep 28 '22 05:09

jdoe