Search code examples
ruby-on-railsrubypostgresqlhstore

Simple Rails array not saving to array column


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.


Solution

  • 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!