5

With Mysql I can use COALESCE to update only the values that are emtpy in a table.

How can I do this with Rails (ActiveRecord)?

I don't want to create if statements for each column in the table and am guessing there has to be a way to do it if I pass an ActiveRecord hash to the update_attributes method.

Thanks.

kakubei
  • 5,321
  • 4
  • 44
  • 66

1 Answers1

-2

It's not so clear what you're asking but if I understand correctly, you want something like this:

class Address < ActiveRecord::Base
  attr_accessible :street, :city, :zip
  def update_null_attributes(hash)
    update_attributes(hash.keep_if { |k,v| __send__("#{v}_was").nil? })
  end
end

This will take the hash of attributes you want to update and pass only the ones that were originally nil. It uses ActiveModel::Dirty for the "#{v}_was" method.

Isaac Betesh
  • 2,935
  • 28
  • 37
  • 2
    Whoever down-voted this answer, would you like to share why? I can't improve the answer if I don't what's wrong with it. – Isaac Betesh Jul 25 '16 at 18:08
  • This was most likely downvoted because it's not atomic. If two resources read the same record at once you'll lose the first write. You would need to lock the record. – zach May 08 '17 at 22:19