Asymmetric associations
In Rails, there are no requirements that both sides of an association be symmetric. In fact, I often find it useful to have asymmetric relationships.
For example, I’m building a mass-mailer. I have parties (people), emails and recipients. Emails are habtm with regards to parties. Since my join table contains other fields besides the two foreign keys, I need a real model for it.
Examine the following code:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Email < ActiveRecord::Base has_many :recipients end class Party < ActiveRecord::Base has_and_belongs_to_many :emails, :join_table => 'recipients' end class Recipient < ActiveRecord::Base belongs_to :email belongs_to :party def read! self.toggle!(:read) end end |
1 2 3 4 5 6 7 8 9 |
>> fbos = Party.find_by_login('fbos') => #<Party:0x3c019d0 ...> >> info = Email.create(:subject => 'Latest Schedule', :body => 'Group schedule: ...') => #<Email:0x3bece38 ...> >> info.recipients.create(:party => fbos) => #<Recipient:0x3bccfd8 ...> >> fbos.emails => [#<Email:0x3b80dc0 ...>] |
1 2 3 4 5 6 7 8 |
class Party < ActiveRecord::Base has_and_belongs_to_many :unread_emails, :join_table => 'recipients', :conditions => 'read = 0' has_and_belongs_to_many :read_emails, :join_table => 'recipients', :conditions => 'read = 1' end |
Please comment or send me an E-Mail at francois.beausoleil@gmail.com to tell me about your experiences with asymmetric relationships.
