ruby - Simple Rails array not saving to array column -
i'm working rails 4.1.0, ruby 2.1.0, , postgres 9.3.0.0.
i'm trying save changes column array of hstores (an array of hashes in ruby parlance).
here's (simplified) code in product model, used saving changes:
def add_to_cart_with_credits(cart) cart.added_product_hashes << {"id" => self.id.to_s, "method" => "credits"} # reason, isn't saving (without exclamation, well) cart.save! end
a few things of note:
- the cart initialised empty array in added_product_hashes column
- i'm storing added products hashes because there couple of ways add products cart, , each require own logic remove , customise.
- each user has own cart, , needs reference later, why carts saved db (instead of using session variable, guess).
any ideas i'm doing wrong? i'm not seeing error: server logs note cart.added_product_hashes
column updates correctly, changes don't persist.
solution
as james pointed out, <<
doesn't flag record being dirty, edits array in-place. while wasn't changing hstores within array column, appears changes enclosing array aren't picked unless attribute explicitly reconstructed. below code fixes problem:
def add_to_cart_with_credits(cart) cart.added_product_hashes = cart.added_product_hashes + [{"id" => self.id.to_s, "method" => "credits"}] # we're go! cart.save! end
james suggests particular method more terse.
see "new data not persisting rails array column on postgres"
activerecord isn't recognizing change array attributes being updated in place.
you can this:
cart.added_product_hashes_will_change!
Comments
Post a Comment