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

栏目: Ruby · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/5130663/preferred-way-to-private-messages-modeling-in-rails-3

我计划在成员之间实现私人消息系统.我想知道什么是首选方法.

要求是

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

@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,  :class_name => 'Message', :foreign_key=> 'to_user_id'
  has_many :messages_sent,      :class_name => 'Message', :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, :from_user => sally, :body => 'hi back')
bob_reply   = first_msg.replies.build(:to_user => sally, :from_user => bob, :body => 'later')

翻译自:https://stackoverflow.com/questions/5130663/preferred-way-to-private-messages-modeling-in-rails-3


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Windows内核原理与实现

Windows内核原理与实现

潘爱民 / 电子工业出版社 / 2010年4月 / 99.00元

本书从操作系统原理的角度,详细解析了Windows如何实现现代操作系统的各个关键部件,包括进程、线程、物理内存和虚拟内存的管理,Windows中的同步和并发性支持,以及Windows的I/O模型。在介绍这些关键部件时,本书直接以Windows的源代码(WRK, Windows Research Kernel)为参照,因而读者可以了解像Windows这样的复杂操作系统是如何在x86处理器上运行的。 ......一起来看看 《Windows内核原理与实现》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换