views:

11

answers:

1

I am working on a project where many ActiveRecord models can have a conversation associated with it. Users can discuss just about every aspect of the site. I have two ideas as to how this should be implemented.

1) Use a belongs_to in the asset, not the conversation - conversation will be totally unaware of its asset

class Product< ActiveRecord::Base
  belongs_to :conversation
end

class PurchaseOrder < ActiveRecord::Base
  belongs_to :conversation
end

2) Use a belongs_to, :polymorphic => true in the conversation

class Conversation < ActiveRecord::Base
  belongs_to :asset, :polymorphic => true
end

class Product < ActiveRecord::Base
  has_one :conversation, :as => :asset
end

class PurchaseOrder < ActiveRecord::Base
  has_one :conversation, :as => :asset
end

Which is the correct way to model this relationship? If I were to state the relationship, I would say that "a product / purchase order may have one conversation".

+1  A: 

I think it depends on what, if anything, one model in the relationship needs to know about the other. Seems to me, from your description that the second approach it more fitting in this case. Why?

  • The Product and PurchaseOrder models are self-contrained entities in the sense that they can exist apart from conversations about them. So you probably don't want foreign keys polluting these models for tacking on conversations. The relationship ought to be unobtrusive in that sense.
  • A Conversation has a logical dependency on the entity it's associated with so it has the asset_id (and asset_type) foreign keys and that's probably reasonable

This is a very common question and one which always has me stopping to think a bit too. It's not always obvious. There's a good article considering the issue here

bjg
Great answer. Thanks for your insight.
retailevolved