class User include Mongoid::Document embeds_many :accounts, cascade_callbacks: true accepts_nested_attributes_for :accounts index({ 'accounts.jid' => 1 }) def update_pass(jid, pass) account_credentials = accounts.detect do |f| f[:jid] == jid || f['jid'] == jid end account_credentials[:pass] = pass save end def self.existing_jid(jid) where('accounts.jid' => jid).only(:accounts).first end def self.create_jid(jid) new_user = new() new_user.add_account(jid) new_user.save new_user end def add_account(another_jid, password = nil) accounts << Account.new(jid: another_jid, pass: password) save end def self.crendentials_for_token(token) user = find_by_token(token) return user ? user.accounts : [] end def self.find_by_token(token) found = Token.where(token: token).only(:user_id).limit(1).first if found return find(found.user_id) else return nil end end def self.can_save_conversation(my_jid, friend_jid, chat_id = nil) if chat_id.blank? found = User.where('accounts.jid' => my_jid) .elem_match('accounts.conversation_settings' => {jid: friend_jid, value: 0}) else found = User.where('accounts.jid' => my_jid) .elem_match('accounts.conversation_settings' => {chat_id: chat_id, value: 0}) end found.first.nil? end end