如何通过ActiveRecord在一个表中将两列指向另一个表中的同一列? [英] How can I have two columns in one table point to the same column in another with ActiveRecord?

查看:95
本文介绍了如何通过ActiveRecord在一个表中将两列指向另一个表中的同一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里冒着从前到后的风险,但是我不太想知道如何使用Rails的ActiveRecord糖来做到这一点。

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

我有一个具有两列的 tickets 表( submitter_id assignee_id ),它们应该分别引用 users 表中的不同用户(特别是 id 列>用户表)。我希望能够使用ActiveRecord进行 ticket.submitter.name ticket.assignee.email 之类的操作协会。提交者和受让人只是具有不同关联名称的用户对象。

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!

推荐答案

class Ticket < ActiveRecord::Base
  belongs_to :submitter, :class_name => "User"
  belongs_to :assignee, :class_name => "User"
end

应该工作。

编辑:如果不尝试,我不确定是否需要:foreign_key参数。我的直觉不是,但不会痛。

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.

无论如何,请尝试:

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

这篇关于如何通过ActiveRecord在一个表中将两列指向另一个表中的同一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆