Skip to content

Instantly share code, notes, and snippets.

@ch1ago
Last active December 21, 2015 20:18
Show Gist options
  • Save ch1ago/6360071 to your computer and use it in GitHub Desktop.
Save ch1ago/6360071 to your computer and use it in GitHub Desktop.
class Cart < ActiveRecord::Base
has_many :cart_lines
accepts_nested_attributes_for :cart_lines, allow_destroy: true
....
end
# the last cart has 2 cart_lines
# let's update these attributes
# as they were copied from our PATCH /carts/1 log
CartLine.pluck :quantity
(2.1ms) SELECT "cart_lines"."quantity" FROM "cart_lines"
=> [1, 1]
attrs = {"cart_lines_attributes"=>{"0"=>{"quantity"=>"2", "id"=>"1"}, "1"=>{"quantity"=>"5", "id"=>"2"}}}
a=Cart.last
Cart Load (1.9ms) SELECT "carts".* FROM "carts" ORDER BY "carts"."id" DESC LIMIT 1
=> #<Cart id: 1, quantity: 2, old_price: #<BigDecimal:bba0b660,'0.0',9(18)>, main_price: #<BigDecimal:bba0b5fc,'0.11E0',9(18)>, cost_price: #<BigDecimal:bba0b598,'0.0',9(18)>, created_at: "2013-08-27 18:16:23", updated_at: "2013-08-27 18:23:10">
a.update_attributes! attrs
(0.9ms) BEGIN
CartLine Load (1.0ms) SELECT "cart_lines".* FROM "cart_lines" WHERE "cart_lines"."cart_id" = $1 AND "cart_lines"."id" IN (1, 2) [["cart_id", 1]]
CartLine Load (2.3ms) SELECT "cart_lines".* FROM "cart_lines" WHERE "cart_lines"."cart_id" = $1 [["cart_id", 1]]
(0.7ms) COMMIT
=> true
irb(main):044:0> a.cart_lines[0].quantity
=> 1
irb(main):045:0> a.cart_lines[1].quantity
=> 1
irb(main):046:0> a.cart_lines(true)[1].quantity
CartLine Load (1.8ms) SELECT "cart_lines".* FROM "cart_lines" WHERE "cart_lines"."cart_id" = $1 [["cart_id", 1]]
=> 1
irb(main):047:0> a.cart_lines(true)[0].quantity
CartLine Load (1.6ms) SELECT "cart_lines".* FROM "cart_lines" WHERE "cart_lines"."cart_id" = $1 [["cart_id", 1]]
=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment