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

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


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'endclass 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