mr_urf
mr_urf

Reputation: 3353

Rails: has_many :through or has_many_and_belongs_to?

I have an app where I want to link an instance of a model to another instance of the same model via another model (i.e. Task1 > Relationship < Task2) and am wondering if I can use has_many :through for this.

Basically, the relationship model would have extra information (type_of_relationship, lag) so it would be ideal to have it as a joining model. However, there are not two models to join, only one … to itself. Would the has_many :through still work? If so, how would the join table look? With Rails conventions you would have two columns called Activity_id, which obviously won’t work in the database.

Alternatively, I can use has_many_and_belongs_to to set up a many-many between the Task model and the Relationship model but I'm not sure if this accurately describes a relationship that should only ever link two Task models in any one Relationship model (although of course the Tasks may belong to more than one Relationship, hence many-many).

My instinct says to go with has_many_and_belongs_to and sort out the rules in the models but is there a better way to do this? I’m going round in circles on this one!

Any help appreciated.

Upvotes: 4

Views: 3697

Answers (1)

Milan Novota
Milan Novota

Reputation: 15596

has_many :through fits perfectly into your situation. I don't know about specifics of your model, but let's say you have users and every user can have other users as contacts. You can model this situation as follows:

class User < ActiveRecord::Base
  has_many :contact_records, :foreign_key => :owner_id
  has_many :contacts, :through => :contact_records, :class_name => "User"
end

class ContactRecord < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  belongs_to :user
end

Upvotes: 8

Related Questions