ruby-on-rails-4mongoid4

Rails 4.1 7 Mongoid Activerecord is autosaving without calling .save


Let me explain first my model structure:

i have a status model:

class Status
  include Mongoid::Document
  include Mongoid::Search
  include Mongoid::Timestamps

  field :status_code, type: Integer
  field :status_description, type: String

  validates :status_code, :status_description, :transactiontype, :presence => true

  belongs_to :transactiontype, :class_name => 'Transactiontype'
  has_many :transactions, :class_name => 'Transaction', autosave: false

  search_in :status_code, :status_description, :transactiontype => :transaction

  def self.getStatus(transactiontype)
    statuses = Status.where(:transactiontype_id => transactiontype).all

    stats = []
    puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
    statuses.each do |status|
      transactions = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
      if transactions.length > 0
        status.transactions = transactions
        stats.push(status)
      end
    end
    puts "SIZE : #{stats.size}"
    stats
  end

  etc..

end

then i have another model called transactions:

class Transaction
  include Mongoid::Document
  include Mongoid::Search
  include Mongoid::Timestamps
  field :ref_no, type: String
  field :trans_date, type: DateTime

  belongs_to :status, :class_name => 'Status'
  belongs_to :transactiontype, :class_name => 'Transactiontype'

  validates :ref_no, :trans_date, :status, :presence => true
  def self.dateRange(startdate,enddate)
    puts "DATE : #{startdate} to #{enddate}"
    if !startdate.blank?
      where(:created_at => {"$gt" => startdate.beginning_of_day, "$lt" => enddate.end_of_day})
      # where(:trans_date.gte => startdate.beginning_of_day, :trans_date.lte => enddate.end_of_day)
    end
  end

  etc..

end

the weird part is that:

when im trying to execute:

Status.getStatus(params[:transactiontype_id])

i received the correct output but the transactions associated with the Status is being updated and each records before the filtered date is being updated with null status_id.

i already tried to add autosave: false but nothing works

can someone help me with this?


Solution

  • the solution is to convert the active record to json first

    def self.getStatus(transactiontype)
        statuses = Status.where(:transactiontype_id => transactiontype).all
    
        stats = []
        puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
        statuses.each do |status|
          ar_status = status.as_json
          ar_status['transactions'] = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
          if ar_status['transactions'].length > 0
            stats.push(ar_status)
          end
        end
        puts "SIZE : #{stats.size}"
        stats
      end
    

    for some reason.. its auto saving the records.