Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
mr_urf Avatar asked Mar 01 '23 01:03

mr_urf


1 Answers

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
like image 147
Milan Novota Avatar answered Mar 05 '23 16:03

Milan Novota