【问题标题】:Multipe relationships in Rails where the class name does not match the association nameRails 中类名与关联名不匹配的多个关系
【发布时间】:2010-01-02 00:08:42
【问题描述】:

我有一个与两个用户相关的私人消息模型,如何设置关联以便 PM.sender 是发件人的用户模型,而 PM.receiver 是收件人的用户模型? (这样我就可以调用 PM.sender.username 等)

我有一个 sender_id 和 receiver_id 字段。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    假设模型类 MessageUser,在您的 Message 模型中:

    class Message < ActiveRecord::Base
      belongs_to :sender, :class_name => 'User'
      belongs_to :receiver, :class_name => 'User'
    end
    

    因为类名不能从关联名中推断出来,所以需要显式的:class_name

    更新:刚刚检查过,:foreign_key 参数不应该是必需的,只要外键的名称是关联名称后跟_id,它就是在这种情况下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2021-10-07
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多