如何使用 ActiveRecord 让一个表中的两列指向另一个表中的同一列?
我在这里冒着手掌到额头的风险,但我不太清楚如何使用 Rails 的 ActiveRecord 糖来做到这一点。
我有一个 tickets
表,其中有两列(submitter_id
和 assignee_id
),每一列应引用与 users
不同的用户code> 表(特别是 users
表中的 id
列)。我希望能够使用 ActiveRecord 的关联执行 ticket.submitter.name
和 ticket.assignee.email
等操作。提交者和受让人只是不同关联名称下的用户对象。
我发现唯一接近我正在做的事情是使用多态关联,但最终我相当确定这并不是我真正需要的。我不会有多种类型,提交者和受让人都将是用户,并且很可能是两个不同的用户。
任何帮助都会很棒。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该有效。
编辑:如果没有尝试过,我不确定您是否需要 :foreign_key 参数。我的直觉不是,但这也无伤大雅。
再次编辑:抱歉,忽略了用户 ->票务协会。您没有提到使用它们,如果我不打算在另一方向使用它们,我通常只会在一个方向添加关联。
无论如何,请尝试:
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:
像这样的东西应该可以工作
是的,PreciousBodilyFluids是对的,我们不需要在Ticket类中指定foreign_key,因为rails可以从列名称中推断它,即submitter_id和assignee_id
但是如果您的关联名称与column_name_{id}不同那么你必须指定它,即 User 类的情况
Something like this should work
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