Rails: has_many :through or has_many_and_belongs_to?

女生的网名这么多〃 提交于 2019-12-10 09:07:42

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/472227/rails-has-many-through-or-has-many-and-belongs-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!