0

让我先解释一下我的模型结构:

我有一个状态模型:

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

然后我有另一个模型称为事务:

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

奇怪的是:

当我试图执行时:

Status.getStatus(params[:transactiontype_id])

我收到了正确的输出,但与状态相关的事务正在更新,并且过滤日期之前的每条记录正在更新为 null status_id。

我已经尝试添加 autosave: false 但没有任何效果

有人可以帮我弄这个吗?

4

1 回答 1

0

解决办法是先把活动记录转成json

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

出于某种原因..它自动保存记录。

于 2015-02-24T09:46:10.047 回答