It seems that Message
should be polymorphic in this case, since they can belong to many different models. Because contacts can send messages to other contacts, Contact
will have two associations with messages, one for sent_messages
and the other for received_messages
. Message
will be tied to a sender through contact_id
.
class Contact < ActiveRecord::Base
belongs_to :company
has_many :enquiries
has_many :sent_messages, :class_name => "Message"
has_many :received_messages, :as => :messageable, :class_name => "Message"
end
class Company < ActiveRecord::Base
has_many :contacts
has_many :messages, :as => :messageable
end
class Enquiry < ActiveRecord::Base
belongs_to :contact
has_many :messages, :as => :messageable
end
class Message < ActiveRecord::Base
belongs_to :contact
belongs_to :messageable, :polymorphic => true
end
This should model your relationship requirements pretty well. If you want to better understand it, the Railscast on Polymorphic Associations might be of some insight as well.