ActiveRecord: save_only_valid_attributes ?

Hello,

I'm looking for a variation on the "save" method, that will only save attributes that do not have errors attached to them.

So a model can be updated without being valid overall, and this will still prevent saving invalid data to the database.

I've been looking through the Rails code for a while now, and I've been unable to find anything that might work. Does anyone have an ideas for how I can accomplish this?

Thanks for your time, Brady

You could solve it by doing something like this?

def save_valid_attributes     self.valid?     self.attributes.each do |k,v|        self.update_attribute(k.to_sym, v) unless self.errors.on(k.to_sym)     end end

Rob Lacey

brady8 wrote:

something like

def save_valid_attributes valid? update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m} end

would save you multiple hits on the db for single attributes. check out Enumerable#inject for more information http://www.ruby-doc.org/core/classes/Enumerable.html#M003160

HTH

RSL

Russell Norris wrote:

def save_valid_attributes   valid?   update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m} end

And note this violates the GUI principle of least surprise.

If a customer were changing credit card and billing address at the same time, they don't need the billing address to stick in the database when the CC bounces.

I'm aware the actual problem may be different here...

it still violates it in the original code. it just violates it with less db hits.

RSL

Thanks, that inject code will work nicely! And yes, I'm a good like interface designer, due to the nature of what I'm working on there is lots of partial updates to data before the model instance is full and valid, and the user is notified that partial updates are saved.

Thanks again, I appreciate it.

-Brady