How can I have two columns in one table point to t

2020-07-07 11:07发布

问题:

I run the risk of palm-to-forehead here, but I can't quite figure out how to do this with Rails' ActiveRecord sugar.

I have a tickets table that has two columns (submitter_id and assignee_id) that should each reference a different user from the users table (specifically the id column in the users table). I'd like to be able to do things like ticket.submitter.name and ticket.assignee.email using ActiveRecord's associations. Submitter and Assignee are simply user objects under different associative names.

The only thing I've found that comes close to what I am doing is using polymorphic associations, but in the end I'm fairly certain that it's not really what I need. I'm not going to have multiple types, both submitter and assignee will be users, and very well could be two different users.

Any help would be fantastic. Thanks!

回答1:

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


回答2:

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