0

Model Listing has a json column named vendors, which defaults to {}:

add_column :listings, :vendors, :json, null: false, default: {
  hd: {}
  ...
  }
end

Inside the Listing class, I am trying to merge! in a hash to hd: {..} like so:

def self.append_vendor_attrs(sku)
  listing = find_by(sku: sku) || Listing.new(sku: sku)
  listing.vendors[:hd].merge!({ foo: 'bar' })
  listing.vendors_will_change!
  listing.save! # throws no exceptions in the log
end

but vendors[:hd] remains empty. if I try to replicate this manually with:

l = Listing.create... 
l.vendors[:hd].merge!({ foo:'bar' })

my hash persists.

3
  • 1
    Have you tried moving listing.vendors_will_change! above the line where you modify the attribute in place? My hunch is that the code you have in your method tells AR that the value of the attribute was the new value, so that it doesn't see the object as dirty when you call save!. Commented Jan 5, 2017 at 14:59
  • @hoffm of course! I was calling will_change after the data was already appended, triggering AR to "listen" to any changes to that row but nothing was changed. Go Brooklyn! Turn this into an answer so I can accept? Commented Jan 5, 2017 at 16:21
  • Glad it worked! I just added an answer. Commented Jan 5, 2017 at 21:56

1 Answer 1

1

Calling listing.vendors_will_change! tells Active Record that the value of the attribute "was" the new value. From AR's perspective, then, the old and new values match, and so the record is not dirty when you call save!.

The fix is to move listing.vendors_will_change! above the line where you modify the attribute. So the new code will look like this:

def self.append_vendor_attrs(sku)
  listing = find_by(sku: sku) || Listing.new(sku: sku)
  listing.vendors_will_change!
  listing.vendors[:hd].merge!({ foo: 'bar' })
  listing.save! # throws no exceptions in the log
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.