model user's message in rails 3

狂风中的少年 提交于 2019-11-28 06:04:35

this is a nice problem! I would model that to compare as closely as possible to the e-mail model. So a message always belongs to a single user, and it was either sent or received.

In short:

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

And the model would like:

class Message < ActiveRecord::Base
  belongs_to :user

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

end

And in the user:

class User    
  has_many :messages
end

You would then simply be able to query all sent messages by

user.messages.sent

and the received messages

user.messages.received

Sending a message does become a bit more complicated then:

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

or something along those lines: you copy the message and attach it to all recipients, and lastly make the original message the sent message.

This way each user has total control over the message.

Possible improvements:

  • also keep an explicit reference to the sender and receiver(s) in the message, to be able to allow replies and stuff
  • instead of working with a single boolean, maybe allow working with folders?

Hope this helps.

You can add two booleans to mark the message as deleted for both sender and receiver. Then after setting either of them check if the message can be deleted permanently.

Example:

create_table "messages", :force => true do |t|
  t.boolean :sender_deleted
  t.boolean :receiver_deleted
end

And in model:

class Message
  def self.delete_message(id)
    m = Message.find(id)
    m.destroy if m.sender_deleted && m.receiver_deleted
  end
end

You can nullify on a deleted record with :dependent=>:nullify

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

You'll need to handle when displaying the message that the sender/receiver of the message has been deleted, since the sender_id or destination_id will be null, but the message will stay intact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!