Theocacao
Leopard
Design Element
Comment on "Attribute Values in Rails"
by Blake Watters — Nov 07
You are making this much too difficult on yourself.

First off, in Active Record models the attributes array is used to hold the values as fetched from the database. The instance variables, or attributes, are manipulated by the programmer and persisted back into the model via save or save!

You can inspect the validity of a model by calling model.valid? or doing:

begin
model.save!
rescue ActiveRecord::RecordInvalid
end

If you need to update an attribute individually or as a hash, ActiveRecord provides update_attribute and update_attributes that update the record and persist the model.

Iteration on the model.attributes array is failing to persist because attributes returns a hash of the attributes with _clones_ of the attribute value.

You might want to start coding with http://api.rubyonrails.com/ open in a tab -- these subtleties are often covered in the RDoc quite nicely.

You could also achieve the same effect by coding:

def scrub_attributes
self.attributes.each do |key,value|
if value.is_a?(String)
value.strip!
value.squeeze!(" ")
self.send("#{key}=", value)
OR
self.update_attribute(key, value)
end
end
end

Though grouping your changes and using update_attributes will result in attributes.size - 1 less DB queries to hydrate the model.
Back to "Attribute Values in Rails"
Design Element

Copyright © Scott Stevenson 2004-2015