Monday, May 7, 2012

Rails: Using no id keys in a has-many-belongs-to association

This small recipe is useful for when you have to link 2 models with no id keys. Our case is for users that can send and receive invitations. The key to make the lookup for the 'invited' users is the email, not an id. Since the 'invited' users could have not completed the registration process, we could not use a 'recipient_id' column. Note that the column used for the lookup takes a different name on both models.
Once built, the relationships are really easy:

class User < ActiveRecord::Base
(...)
   has_many :invitations_sent,
      :foreign_key => 'user_id',
      :class_name => 'Invitation', :dependent => :destroy, :inverse_of => :user
   has_many :invitations_received,
      :primary_key => 'email', :foreign_key => 'recipient_email',
      :class_name => 'Invitation', :inverse_of => :recipient
(...)
end




class Invitation < ActiveRecord::Base
(...)
   belongs_to :user, :inverse_of => :invitations_sent
   belongs_to :recipient,
      :primary_key => 'email', :foreign_key => 'recipient_email',
      :class_name => 'User', :inverse_of => :invitations_received
(...)
end


Et voila!