如何使用Mongoid + Rails访问从祖父到孙子的文档 3.


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

关于jobs行动的user_controller.rb

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 过滤所有作业?

有更好的方法吗?

您可以在以下行上执行一些操作,仍然很少有数据库请求,但由于连接不可用,这是意料之中的。但它会比你现在做的数据库请求少:

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))

相关内容

  • 没有找到相关文章

最新更新