Associations are great in Rails. There is a ton of functionality baked right in. One such feature is the ability to change the name of association columns.
This is the first post in a series
- 1. Custom named belongs_to associations in Rails with foreign key constraints
- 2. Using custom named association columns in a Rails migration
First, lets talk through some setup data. We are working with two models: Journal and User. And their respective association:
- A User has_many Journals
- A Journal belongs_to a User
Your models currently look like the following:
Assuming the above already exists, now we want to ensure a reference between the two models with a user_id column on the Journal. At this point you could use the following command to build that migration
Test driving this in a console should work with the above associations
Who is the creator of the Journal?
The previous setup works as you would expect, but what if you wanted to better describe
who created a Journal without changing the classname for User?
You might want a column named
creator that stores the user who created the journal.
This would allow for more readable association language for future developers.
Rails has some built in support to achieve just this using some additional arguments within the belongs_to method. Note: this requires no changes to the User model.
Our model now responds to the column name creator the same way it would to a standard user reference.
One step further
You can improve on this approach by adding an index and foreign key to the creator_id column in the migration. This ensures referential integrity as well as speeding up any queries based on creator_id.
Now you have a custom named column, that is constrained based on a foreign key , and indexed for faster querying. There are plenty of other tricks with associations that can also be found on Rails Guides.comments powered by Disqus