2

I'm working with Rails 4.1.0, Ruby 2.1.0, and Postgres 9.3.0.0.

I'm trying to save changes to a column which is an array of hstores (an array of hashes in ruby parlance).

Here's the (simplified) code in the product model, used for saving the changes:

def add_to_cart_with_credits(cart)
    cart.added_product_hashes << {"id" => self.id.to_s, "method" => "credits"}
    # For some reason, this isn't saving (without the exclamation, as well)
    cart.save!
end

A few things of note:

  1. The cart is initialised with an empty array in the added_product_hashes column
  2. I'm storing added products as hashes because there are a couple of ways to add products to the cart, and they each require their own logic to remove and customise.
  3. Each user has their own cart, and needs to reference it later, which is why carts are saved to the DB like this (instead of using a session variable, I guess).

Any ideas what I'm doing wrong? I'm not seeing an error: the server logs note that the cart.added_product_hashes column updates correctly, but the changes don't persist.

SOLUTION

As James pointed out, << doesn't flag the record as being dirty, as it edits the array in-place. While I wasn't changing the hstores themselves within the array column, it appears that changes to the enclosing array aren't picked up unless the attribute is explicitly reconstructed. The below code fixes the problem:

def add_to_cart_with_credits(cart)
    cart.added_product_hashes = cart.added_product_hashes + [{"id" => self.id.to_s, "method" => "credits"}]
    # Now we're all good to go!
    cart.save!
end

James also suggests a particular method that would be more terse.

Sam Morgan
  • 228
  • 1
  • 11
  • 2
    Have you tried using the new JSON column type? Rails seems to handle serialization of that data much better. – tadman Aug 18 '14 at 15:43
  • I'd rather not switch straight across to another column type, as I've only recently moved to hstores! Thanks for the tip, though: I'll check it out now. – Sam Morgan Aug 18 '14 at 15:47
  • It should be a pretty easy migration and would open up other ways of storing your data. I've always found HSTORE to be really fussy to use. The new GIN index options in Postgres 9.3 and the manipulators coming in 9.4 make the JSON column type really potent. Plus, Rails 4 understands them intrinsically. – tadman Aug 18 '14 at 16:25

1 Answers1

5

See "New data not persisting to Rails array column on Postgres"

ActiveRecord isn't recognizing the change to the array as attributes are being updated in place.

You can also do something like this:

cart.added_product_hashes_will_change!
Community
  • 1
  • 1
JamesDullaghan
  • 1,230
  • 11
  • 12
  • Yep, spot-on. I wound up setting the added_product_hashes attribute directly instead of using << to modify it in-place. Apparently using << fails to flag the record as dirty. I'll post the solution above, and thank you! – Sam Morgan Aug 18 '14 at 16:11