I am making a private message system and I’m using state machine for to know where is a message.
This is my model:
class Message
include Mongoid::Document
include Mongoid::Timestamps::Created
#fields
field :subject, :type => String
field :body, :type => String
field :place, :type => String
field :has_been_read, :type => String
# Relationships
belongs_to :sender, :class_name => 'User', :inverse_of => :messages_sent
belongs_to :receiver, :class_name => 'User', :inverse_of => :messages_received
#state machine has been read message?
state_machine :has_been_read, :initial => :unread do
event :read_message do
transition :from => :unread, :to => :read
end
event :mark_unread do
transition :from => :read, :to => :unread
end
end
#state machine status can be in_box, sent, draft, trash, spam
end
user model:
class User
include Mongoid::Document
include Mongoid::Timestamps::Created
.
.
.
has_many :messages_sent, :class_name => 'Message', :inverse_of => :sender
has_many :messages_received, :class_name => 'Message', :inverse_of => :receiver
.
.
.
end
1º How can a message is at the same time on sent or inbox place?
2º What initial state have a message for sender and receiver user?
Sorry but I’m newbie with state_machine gem
Thank you very much
It looks like you’re trying to track two things here (read status and delivery state) and you’re currently combining them together. I think it actually makes sense and would be much cleaner to keep these separate.
I would recommend the following:
In your state-machine, keep track of the message state: draft, outbox, sent, inbox, trash, etc.
Separately keep a
read_atfield in your model that stores the datetime that the message was viewed by the recipient and default this value to nil.field :read_at, type: DateTime, default: nilAdd a boolean method to your document for checking read status:
def read?!@read_at.nil?end