Skip to content

Instantly share code, notes, and snippets.

@markmcspadden
Created March 23, 2012 21:51
Show Gist options
  • Save markmcspadden/2175428 to your computer and use it in GitHub Desktop.
Save markmcspadden/2175428 to your computer and use it in GitHub Desktop.
What Rails does with STI classes when using Polymorphic associations
Loading development environment (Rails 3.2.2)
1.9.3p0 :001 > car = Car.new()
=> #<Car id: nil, name: nil, borrowable_id: nil, borrowable_type: nil, created_at: nil, updated_at: nil>
1.9.3p0 :002 > student = Student.new
=> #<Student id: nil, name: nil, type: "Student", created_at: nil, updated_at: nil>
1.9.3p0 :003 > student.save
(0.3ms) begin transaction
SQL (8.8ms) INSERT INTO "staffs" ("created_at", "name", "type", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Fri, 23 Mar 2012 21:37:53 UTC +00:00], ["name", nil], ["type", "Student"], ["updated_at", Fri, 23 Mar 2012 21:37:53 UTC +00:00]]
(56.4ms) commit transaction
=> true
1.9.3p0 :004 > student.car = car
Car Load (0.2ms) SELECT "cars".* FROM "cars" WHERE "cars"."borrowable_id" = 1 AND "cars"."borrowable_type" = 'Staff' LIMIT 1
(0.0ms) begin transaction
SQL (0.6ms) INSERT INTO "cars" ("borrowable_id", "borrowable_type", "created_at", "name", "updated_at") VALUES (?, ?, ?, ?, ?) [["borrowable_id", 1], ["borrowable_type", "Staff"], ["created_at", Fri, 23 Mar 2012 21:38:00 UTC +00:00], ["name", nil], ["updated_at", Fri, 23 Mar 2012 21:38:00 UTC +00:00]]
(51.0ms) commit transaction
=> #<Car id: 1, name: nil, borrowable_id: 1, borrowable_type: "Staff", created_at: "2012-03-23 21:38:00", updated_at: "2012-03-23 21:38:00">
1.9.3p0 :005 > car.borrowable
Staff Load (0.3ms) SELECT "staffs".* FROM "staffs" WHERE "staffs"."id" = 1 LIMIT 1
=> #<Student id: 1, name: nil, type: "Student", created_at: "2012-03-23 21:37:53", updated_at: "2012-03-23 21:37:53">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment