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.
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
Given this information you might come up with something like
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.