Skip to content

Instantly share code, notes, and snippets.

@johnreilly
Created September 1, 2009 18:08
Show Gist options
  • Save johnreilly/179261 to your computer and use it in GitHub Desktop.
Save johnreilly/179261 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
# Columns:
# id, integer
# my_id, string
# etc...
has_one :contact, :primary_key => "my_id", :foreign_key => "my_id"
end
class Contact < ActiveRecord::Base
# Columns:
# id, integer
# my_id, string
# etc...
belongs_to :user, :primary_key => "my_id", :foreign_key => "my_id"
end
### Get a reference to a user
>> user = User.first
User Load (0.3ms) SELECT * FROM "users" LIMIT 1
=> #<User id: 1, my_id: "54feb156">
### Does the user have a contact associated? No.
>> user.contact
Contact Load (0.2ms) SELECT * FROM "contacts" WHERE ("contacts".my_id = '54feb156') LIMIT 1
=> nil
### Give the user a contact
>> user.contact = Contact.new
Contact Load (0.1ms) SELECT * FROM "contacts" WHERE ("contacts".my_id = '54feb156') LIMIT 1
Contact Create (0.6ms) INSERT INTO "contacts" ( "my_id" ) VALUES('54feb156')
=> #<Contact id: 12, my_id: "54feb156">
### Does the user have a contact associated? Yes!
>> user.contact
=> #<Contact id: 12, my_id: "54feb156">
### Save the user. Contact's my_id is set to user's id!?
>> user.save
User Update (0.8ms) UPDATE "users" SET "perishable_token" = '0BIrKc54inzvSQhAc2uq' WHERE "id" = 1
Contact Update (0.1ms) UPDATE "contacts" SET "updated_at" = '2009-09-01 17:55:46', "my_id" = 1 WHERE "id" = 12
###
### Why is "my_id" set to 1 in the above update?
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment