aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/association_basics.md
diff options
context:
space:
mode:
authorZachary Scott <e@zzak.io>2015-04-10 17:28:22 -0700
committerZachary Scott <e@zzak.io>2015-04-10 17:28:22 -0700
commit409460e440783b315077cca1b1e435107aa270a0 (patch)
tree1c22d5401b7be31c3dd9d861bf12e8d48315b25f /guides/source/association_basics.md
parent77a7c4bf7d2ed73cbc2554ef9f0514f6191b2658 (diff)
parentd2998764c5ec6f84f55a1a27e74a711c3f043d6a (diff)
downloadrails-409460e440783b315077cca1b1e435107aa270a0.tar.gz
rails-409460e440783b315077cca1b1e435107aa270a0.tar.bz2
rails-409460e440783b315077cca1b1e435107aa270a0.zip
Merge branch 'girishso-belongs_to_primary_key_doc'
Diffstat (limited to 'guides/source/association_basics.md')
-rw-r--r--guides/source/association_basics.md20
1 files changed, 20 insertions, 0 deletions
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index ec6017ff73..d8dcf75740 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -829,6 +829,7 @@ The `belongs_to` association supports these options:
* `:counter_cache`
* `:dependent`
* `:foreign_key`
+* `:primary_key`
* `:inverse_of`
* `:polymorphic`
* `:touch`
@@ -913,6 +914,25 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+##### `:primary_key`
+
+By convention, Rails assumes that the `id` column is used to hold the primary key of it's table.
+The `:primary_key` option allows you to specify a different column.
+
+For example, given we have a `users` table with `guid` as the primary key. If we want a separate `todos` table to hold the foreign key `user_id` in the `guid` column, then we can use `primary_key` to achieve this like so:
+
+```ruby
+class User < ActiveRecord::Base
+ self.primay_key = 'guid' # primary key is guid and not id
+end
+
+class Todo < ActiveRecord::Base
+ belongs_to :user, primary_key: 'guid'
+end
+```
+
+When we execute `@user.todos.create` then the `@todo` record will have `user_id` value as the `guid` value of `@user`.
+
##### `:inverse_of`
The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. Does not work in combination with the `:polymorphic` options.