johnreilly (owner)

Revisions

gist: 179261 Download_button fork
public
Public Clone URL: git://gist.github.com/179261.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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?
###