sql – Rails – 一个模型上的两个外键都是指相同的型号

前端之家收集整理的这篇文章主要介绍了sql – Rails – 一个模型上的两个外键都是指相同的型号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对ActiveRecord关联来说相当新鲜.我正在绘制一个应用程序,用于跟踪在一组用户之间谁欠彼此的钱.费用模型和用户模型似乎是自然选择,我不知道如何定义两者之间的关系.例如,我想跟踪债权人(“所有者”)和每笔费用的债务人,但这只是两个外键返回给用户.此外,每个用户可以拥有多个费用(作为债权人和债务人)我迄今为止对于协会的最好猜测是:
class Expense
    # belongs_to or has_one here?
    # Not sure about class => User Syntax:
    # need to alias to foreign keys that reference the same model
    belongs_to :creditor,:class => User 
    belongs_to :debtor,:class => User

class User
    # has_many expenses defines a creditor relationship (user owns expense)
    # how to define debtor relationship? (belongs_to...?)
    has_and_belongs_to_many :expenses

我已经阅读了关于协会的Rails指南,但是在外键和连接表上我仍然相当失落.任何输入都非常感激!

解决方法

所以这绝对不是一个关于多对多关系的has_and_belongs_to_many.你只需要使用几个has_many关系.我认为应该最终看起来像这样:

编辑:哎哟,我很抱歉,有一点对不起,让我有另一个去:

class Expense
  # make sure expense table has 'creditor_id' and 'debtor_id' rows
  belongs_to :creditor,:class_name => "User",:foreign_key => :creditor_id
  belongs_to :debtor,:foreign_key => :debtor_id

class User
  has_many :debts,:class_name => "Expense",:foreign_key => :debtor_id
  has_many :credits,:foreign_key => :creditor_id
原文链接:https://www.f2er.com/mssql/75904.html

猜你在找的MsSQL相关文章