Emmanuel Pastor bio photo

Emmanuel Pastor

Software polymath, application architect, code craftsman.

Twitter

LinkedIn

Github

Ruby on Rails Pro Tip: Multiple associations to the same model

This is the first post in a series focused on quick, easy to digest Ruby on Rails tips.

   

Sometimes we need to create multiple associations between the same models in a Rails application, consider for instance that a Blog model has one owner and also one administrator, both associate the Blog model with the User model, also consider that a User could be the owner of many blogs and also the admin of many others.

   

In order to have multiple associations between the same objects, we need to specify different attribute names and the appropriate :class and :foreign_key while defining the association in our ActiveRecord models:

   

./app/models/user.rb

class User < ActiveRecord::Base
has_many :owned_blogs, class_name: "Blog", foreign_key: "blog_owner_id"
has_many :managed_blogs, class_name: "Blog", foreign_key: "blog_manager_id"

./app/models/blog.rb

class Blog < ActiveRecord::Base
belongs_to :blog_owner, class_name: "User", foreign_key: "blog_owner_id"
belongs_to :blog_manager, class_name: "User", foreign_key: "blog_manager_id"


comments powered by Disqus