加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3中私有消息建模的首选方法

发布时间:2020-12-17 04:35:50 所属栏目:百科 来源:网络整理
导读:我计划在成员之间实现私人消息系统.我想知道什么是首选方法. 要求是 我应该能够像这样轻松地检索它们 @user.conversations #Should return User objects that I sent or received messages from (but not me)@user.conversations.messages #Messages from al
我计划在成员之间实现私人消息系统.我想知道什么是首选方法.

要求是

>我应该能够像这样轻松地检索它们

@user.conversations               #Should return User objects that I sent or received messages from (but not me)
@user.conversations.messages      #Messages from all or specific user objects.
@user.conversations.messages.unread      #Unread messages

>当调用@ user.conversations时,应仅检索向我发送消息的人或发送消息的人.应排除current_user.
>如果我是sender_id = 5并发送to_id = 10那么,另一个人将回复发件人= 10 to_id = 5.这应该被视为并理解为相同的会话对象.

关于最后一点.我不确定什么是建模的首选方法.

最好使用一个Conversation模型来处理所有消息,例如

attr_accessible :user_id,:friend_id,:message,:read
    belongs_to :user

或者,最好创建一个Conversation模型来处理关联和消息的Message模型.

我想看看如何实现这种关系的示例,以及是否有其他方法可以实现.

我在这里有点迷失.

解决方法

一个更简单的模型是捕获每个消息:
class Message < ActiveRecord::Base
  belongs_to :from_user,:class_name => 'User' # from_user_id field fk Users
  belongs_to :to_user,:class_name => 'User' # to_user_id field fk Users
  belongs_to :thread,:class_name => 'Message'  # Reference to parent message
  has_many :replies,:class_name => 'Message',:foreign_key => 'thread_id'

  named_scope :in_reply_to,lambda { |message| :conditions => {:thread => message},:order => 'created_at' }
end

class User < ActiveRecord::Base
  has_many :messages_received,:foreign_key=> 'to_user_id'
  has_many :messages_sent,:foreign_key=> 'from_user_id'
end

如果您需要捕获消息线程,那么任何回复消息都可以存储对开始对话(又称为线程)的初始消息的引用.例如:

first_msg   = Message.new(:to_user => bob,:from_user => sally,:body => 'Hello!')
sally_reply = first_msg.replies.build(:to_user => bob,:body => 'hi back')
bob_reply   = first_msg.replies.build(:to_user => sally,:from_user => bob,:body => 'later')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读