1
class User
 include Mongoid::Document
 has_many :orders
 has_one :payments
end

class Order
 include Mongoid::Document
 belongs_to :user
 has_one :payment, dependent: :destroy, :autosave => true
end

class Payment
 include Mongoid::Document
 belongs_to :order
 belongs_to :user
ebd

user_controller.rb行动上jobs

def jobs
 #
 #
 jobs = Order.where(:seller_id => current_user.id).order_by :created_at, :desc
 @jobs = []
 for j in jobs
  if j.payment.preapproval_key != nil && j.payment.correlation_id != nil && j.payment.approved == true
   @jobs << j
  end
 end
 #
 #
end

payment.preapproval_key != nil && payment.correlation_id != nil && payment.approved == true是否可以在不使用此循环的情况下过滤所有作业?

有更好的方法来做到这一点吗?

4

1 回答 1

2

您可以在以下几行中做一些事情,仍然很少有数据库请求,但由于连接不可用,这是可以预料的。但它会小于您现在正在执行的 db 请求:

all_order_ids = Order.where(:seller_id => current_user.id).only(:_id).map(&:id)
payments = Payment.where(:order_id.in => all_order_ids, 
                         :preapproval_key.ne => nil,
                         :correlation_id.ne => nil,
                         :approved => true)
jobs = Order.where(:_id.in => payments.only(:order_id).map(&:order_id))
于 2013-01-22T04:34:32.940 回答