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

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

Computational Advertising

Computational Advertising

by Kushal Dave、Vasudeva Varma / Now Publishers Inc / 2014

Computational Advertising (CA), popularly known as online advertising or Web advertising, refers to finding the most relevant ads matching a particular context on the Web. The context depends on the t......一起来看看 《Computational Advertising》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具