Does the ActiveModel module have a module that includes the update_attributes method?

I installed the ActiveModel class in my Rails application, for example:

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 do this:

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

I could just write update_attributes myself, but I have a feeling that it exists somewhere. It?

+7
source share
2 answers

No, but there is a common template 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 

This is from here. See link for examples.

If you often repeat this approach, you can extract this method in a separate module and include it on demand.

+7
source

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

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

You should be able to enable the module:

 include ActiveModel::AttributeAssignment 
0
source

All Articles