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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With