ruby-on-rails – 在rails 3中的模型用户的消息

我已经建立了以下模型来处理用户的消息交换:
create_table "messages",:force => true do |t|
    t.integer  "source_id"
    t.integer  "destination_id"
    t.string   "object"
    t.string   "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

这些是它的关联:

class Message < ActiveRecord::Base
  belongs_to :sender,:class_name=>'User',:foreign_key=>'source_id'
  belongs_to :reciever,:foreign_key=>'destination_id'
end

而另一方面则是另一方的关联(用户模型):

has_many :sent_messages,:class_name=> 'Message',:foreign_key=>'source_id',:dependent=>:destroy
  has_many :recieved_messages,:foreign_key=>'destination_id',:dependent=>:destroy

该模型是正确的,正常工作,实际上从消息我可以检索谁是发件人,谁是接收者,从用户,我可以得到所有发送和接收的消息.不幸的是,它不处理任何情况:如果接收者或发件人删除消息怎么办?消息是唯一的,所以它消失在双方(坏事).如何知道一方是否已经阅读了这个消息?
任何建议?你认为我必须重新建模吗?
TNX

解决方法

这是一个很好的问题!我会建模,以尽可能的比较电子邮件模型.所以一个消息总是属于一个用户,它是发送或接收的.

简而言之:

create_table "messages",:force => true do |t|
    t.integer  :user_id
    t.string   :subject
    t.string   :body
    t.boolean  :sent
  end

而这个模型就像:

class Message < ActiveRecord::Base
  belongs_to :user

  scope :sent,where(:sent => true)
  scope :received,where(:sent => false)

end

而在用户中:

class User    
  has_many :messages
end

然后,您就可以通过查询所有发送的消息

user.messages.sent

和收到的消息

user.messages.received

发送消息确实变得复杂得多:

class Message

  def send_message(from,recipients)
    recipients.each do |recipient|
      msg = self.clone
      msg.sent = false
      msg.user_id = recipient
      msg.save
    end
    self.update_attributes :user_id => from.id,:sent => true
  end   
end

或沿着这些方向的东西:您复制邮件并将其附加到所有收件人,最后将原始邮件发送给发送的邮件.

这样每个用户都可以完全控制消息.

可能的改进:

>还要保留消息中的发件人和接收者的明确引用,以便能够允许回复内容
>而不是使用单个布尔值,也许允许使用文件夹?

希望这可以帮助.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...