How can I have two columns in one table point to the same column in another with ActiveRecord?

…衆ロ難τιáo~ 提交于 2019-12-04 04:16:15
class Ticket < ActiveRecord::Base
  belongs_to :submitter, :class_name => "User"
  belongs_to :assignee, :class_name => "User"
end

Should work.

Edit: Without trying it out, I'm not sure whether you need the :foreign_key parameter or not. My instinct is not, but it couldn't hurt.

Edit again: Sorry, left off the User -> Ticket associations. You didn't mention using them, and I typically will only add associations in one direction if I don't plan on using them in the other direction.

Anyway, try:

class User < ActiveRecord::Base
  has_many :assigned_tickets, :class_name => "Ticket", :foreign_key => "assignee_id"
  has_many :submitted_tickets, :class_name => "Ticket", :foreign_key => "submitter_id"
end

Something like this should work

class Ticket < ActiveRecord::Base
  belongs_to :submitter, :class_name => 'User', :foreign_key => 'submitter_id'
  belongs_to :assignee,  :class_name => 'User', :foreign_key => 'assignee_id'
end

class User < ActiveRecord::Base
  has_many :tickets, :class_name => 'Ticket', :foreign_key => 'submitter_id'
  has_many :tickets_assigned,  :class_name => 'Ticket', :foreign_key => 'assignee_id'
end

Yes, PreciousBodilyFluids is right we don't need to specify the foreign_key in the Ticket class as rails can infer it from the column name, i.e. submitter_id and assignee_id

But if your association name is different from the column_name_{id} then you will have to specify it, i.e. the User class case

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