Custom foreign keys on Ruby on Rails Active Record

ActiveRecord, like all ORM’s, is one of the greatest things on earth, IMHO :)

By using the Convention or Configuration approach, ActiveRecord and even Rails, allows you to skip a few parts and go straight to what matters: the development.

sometimes, though, the “Sensible defaults” of rails and ActiveRecord are’t enough, but like most ORM’s, the convention can easily be overridden in order to get things done.

When you add a relationship between classes all you have to do is to add a references and has_many on the other side. If you follow the naming rules everything works.

But sometimes you just can’t follow the rules. Let’s see an example.

Upgrade your computer with an SSD

A message is sent from one user to another user. How can you do the mapping, knowing who is the sender and who is the recipient?

In this particular situation you have to specify custom foreign keys. Let’s assume you have two classes: User and Message.

class Message<ActiveRecord::Base
  belongs_to :sender, :class_name => "User", :foreign_key => 'sender_id'
  belongs_to :recipient, :class_name => "User", :foreign_key => 'recipient_id'

Now you can access both the sender and the recipient for each message.

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>