对用户之间的消息建模

发布于 2024-07-10 23:27:12 字数 746 浏览 8 评论 0原文

我想对用户之间的消息进行建模,要求如下:

  1. 用户已接收和发送消息,并且应该由user.received_messagesuser.sent_messages检索< /p>

  2. 消息有发送者和接收者,应通过message.sendermessage.receiver

我已将用户模型创建为:

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

但我不知道如何对用户进行建模,任何建议都会受到赞赏。

I want to model messages between users, here is the requirement:

  1. User has received and sent messages, and should be retrieved by user.received_messages and user.sent_messages

  2. Message has sender and receiver, and should be retrieved by message.sender and message.receiver.

I have created the User model as:

script/generate model User name:string

and Message model as:

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

I have come up with the Message like below, and it works as wish

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

but I don't know how to model the User, any advise is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

允世 2024-07-17 23:27:12

就像消息模型中一样:

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

Just as in the Message model:

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
甜尕妞 2024-07-17 23:27:12

@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"

肯尼

@eric2323223

If you just copy/pasted the code from Milan, then I suspect the error you're seeing is because there's a missing semi-colon in front of 'foreign_key'.

The lines should read:

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

Kenny

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文