【问题标题】:help with rails associations帮助 Rails 协会
【发布时间】:2009-11-30 22:32:20
【问题描述】:

我想为我的应用实现一个消息系统。

我有用户。

我究竟应该怎么做? 创建一个带有两个用户外键的消息模型??......完成这项工作的最合适的方法是什么?

我担心的是,如果我查询“message.user”,我将不知道我是否会得到消息接收者的发件人

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    使用具有适当命名belongs_to 关系的两个单独的外键来区分发送者和接收者。

    给定带有外键 sender_idreceiver_id 的消息模型,您可以这样做:

    class Message < ActiveRecord::Base
      belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
      belongs_to :receiver, :class_name => "User", :foreign_key => "receiver_id"
    end
    

    现在您可以使用message.sender 引用消息的发件人,使用message.receiver 引用收件人。

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 2016-11-01
      • 2011-03-17
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多