app/models/history.rb
3633033b
 class History
 	include Mongoid::Document
 
 	field :me, type: String
 	field :_with, type: String
 
     embeds_many :messages, cascade_callbacks: true
     accepts_nested_attributes_for :messages
 
     index({ me: 1, _with: 1 }, { unique: false })
 
     def self.find_me_with(me, with)
         where(me: me, _with: with).limit(1).first
     end
 
     def self.save_message(me, from, message, chat_with, chat_id = nil)
         _with = chat_id.blank? ? chat_with : chat_id
         history = find_me_with(me, _with)
 
         history = History.new(me: me, _with: _with) if history.nil?
 
         record = Message.new(message: message, from: from)
         history.messages << record
 
         history.save
     end
 end