我建立了以下模型来处理用户的消息交换:
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, :class_name=>'User', :foreign_key=>'destination_id'
end
这些是另一侧的关联(用户模型):
has_many :sent_messages, :class_name=> 'Message', :foreign_key=>'source_id', :dependent=>:destroy
has_many :recieved_messages, :class_name=> 'Message', :foreign_key=>'destination_id', :dependent=>:destroy
该模型是正确的并且可以正常工作,实际上,从消息中我可以检索出谁是发送者,谁是接收者以及从用户那里,我可以获取所有已发送和已接收的消息。不幸的是,它无法处理任何情况:接收方或发送方删除邮件该怎么办?该消息是唯一的,因此在双方都消失了(不好的事情)。如何知道一方是否已经阅读过该消息?
有什么建议吗?您认为我必须重新计划模型吗?
特纳克斯
最佳答案
这是一个很好的问题!我将建模以尽可能与电子邮件模型进行比较。因此,一条消息始终属于一个用户,它既已发送也已接收。
简而言之:
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
或类似的方式:复制邮件并将其附加到所有收件人,最后将原始邮件作为已发送邮件。
这样,每个用户都可以完全控制该消息。
可能的改进:
希望这可以帮助。
关于ruby-on-rails - Rails 3中模型用户的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5141564/