Skip to content

Commit

Permalink
Merge branch 'girishso-belongs_to_primary_key_doc'
Browse files Browse the repository at this point in the history
  • Loading branch information
Zachary Scott committed Apr 11, 2015
2 parents 77a7c4b + d299876 commit 409460e
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions guides/source/association_basics.md
Expand Up @@ -829,6 +829,7 @@ The `belongs_to` association supports these options:
* `:counter_cache`
* `:dependent`
* `:foreign_key`
* `:primary_key`
* `:inverse_of`
* `:polymorphic`
* `:touch`
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit 409460e

Please sign in to comment.