Created
November 12, 2011 23:02
-
-
Save simon-weber/1361260 to your computer and use it in GitHub Desktop.
Rails: for 'a belongs_to b', a.b.id != a.b_id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
irb(main):010:0> t = Tag.new(:rfid => 999, :item_id => 1) | |
=> #<Tag id: nil, rfid: 999, created_at: nil, updated_at: nil, item_id: 1> | |
irb(main):011:0> t.item | |
=> #<Item id: 1, description: "burger", price: #<BigDecimal:b6f6f46c,'0.5E1',4(8)>, created_at: "2011-11-12 03:16:19", updated_at: "2011-11-12 03:16:19"> | |
irb(main):012:0> t.item_id = 2 | |
=> 2 | |
irb(main):013:0> t.save | |
=> true | |
irb(main):016:0> t | |
=> #<Tag id: 1, rfid: 999, created_at: "2011-11-12 22:42:49", updated_at: "2011-11-12 22:42:49", item_id: 2> | |
irb(main):017:0> t.item | |
=> #<Item id: 1, description: "burger", price: #<BigDecimal:b6f35fa0,'0.5E1',4(8)>, created_at: "2011-11-12 03:16:19", updated_at: "2011-11-12 03:16:19"> | |
irb(main):018:0> t.item.id == t.item_id | |
=> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to reload the association after saving the Tag.
ruby-1.9.2-p290 :004 > t = Tag.new(:rfid => 999, :item_id => 1)
=> #<Tag id: nil, rfid: 999, item_id: 1, created_at: nil, updated_at: nil>
ruby-1.9.2-p290 :005 > t.item
Item Load (0.1ms) SELECT "items".* FROM "items" WHERE "items"."id" = 1 LIMIT 1
=> #<Item id: 1, description: "burger", price: #BigDecimal:7fb974c38d60,'0.3599E2',18(18), created_at: "2011-11-13 05:11:05", updated_at: "2011-11-13 05:11:05">
ruby-1.9.2-p290 :006 > t.item_id = 2
=> 2
ruby-1.9.2-p290 :007 > t.save
SQL (8.9ms) INSERT INTO "tags" ("created_at", "item_id", "rfid", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sun, 13 Nov 2011 05:17:29 UTC +00:00], ["item_id", 2], ["rfid", 999], ["updated_at", Sun, 13 Nov 2011 05:17:29 UTC +00:00]]
=> true
ruby-1.9.2-p290 :008 > t
=> #<Tag id: 2, rfid: 999, item_id: 2, created_at: "2011-11-13 05:17:29", updated_at: "2011-11-13 05:17:29">
ruby-1.9.2-p290 :009 > t.reload
Tag Load (0.1ms) SELECT "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT 1 [["id", 2]]
=> #<Tag id: 2, rfid: 999, item_id: 2, created_at: "2011-11-13 05:17:29", updated_at: "2011-11-13 05:17:29">
ruby-1.9.2-p290 :010 > t.item
Item Load (0.1ms) SELECT "items".* FROM "items" WHERE "items"."id" = 2 LIMIT 1
=> #<Item id: 2, description: "burger", price: #BigDecimal:7fb973915aa8,'0.3599E2',18(18), created_at: "2011-11-13 05:12:02", updated_at: "2011-11-13 05:12:02">
ruby-1.9.2-p290 :011 > t.item.id == t.item_id
=> true
ruby-1.9.2-p290 :012 >