在用户之间建模消息

时间:2008-12-24 11:03:18

标签: ruby-on-rails modeling

我想在用户之间建模消息,这是要求:

  1. 用户已收到并发送了邮件,应由user.received_messagesuser.sent_messages

  2. 检索
  3. 消息包含发件人和收件人,应由message.sendermessage.receiver检索。

  4. 我已将用户模型创建为:

    script/generate model User name:string
    

    和消息模型为:

    script/generate model Message content:text sender_id:integer receiver_id:integer
    

    我已经提出了如下所示的消息,它按照愿望运作

    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
    

    但我不知道如何为用户建模,任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:2)

与消息模型一样:

class User < ActiveRecord::Base
  has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
  has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"
end

答案 1 :(得分:1)

@ eric2323223

如果您只是从米兰复制/粘贴代码,那么我怀疑您看到的错误是因为'foreign_key'前面缺少分号。

这些行应为:

  has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
  has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"

肯尼