[英]Rails Active Record Ordering through multiple joins
I have the following relationships. 我有以下关系。
AdhocBkg
has_many :invoice_trans
InvoiceTran
belongs_to :invoice_hdr
belongs_to :meal
InvoiceHdr
belongs_to :supplier
belongs_to :client
I need to pull out All AdhocBkgs with a 'Billed' status and then sort them by: supplier name, client name, inv no, inv tran date and meal sort sequence BUT via the last invoice transaction for each AdhocBkg. 我需要以“结算”状态提取所有AdhocBkgs,然后按以下方式对它们进行排序:供应商名称,客户名称,inv no,inv tran date和meal sort sequence,但是通过每个AdhocBkg的最后一次发票交易。
My current code is : 我目前的代码是:
#AdhocBkg Billed Status ID
abbilledstatusid = AdhocBkgStatus.find_by_abstatdesc('Billed').id
@adhocbkgs = AdhocBkg.find_all_by_abstatusid(abbilledstatusid)
@adhocbkgs.sort! {|x,y| x.invoice_trans.last.invoice_hdr.supplier.suppname + x.invoice_trans.last.invoice_hdr.client.clientname + x.invoice_trans.last.invoice_hdr.invno.to_s + x.invoice_trans.last.invtrndate.strftime('%Y%m%d') + x.invoice_trans.last.meal.mealsortseq.to_s <=> y.invoice_trans.last.invoice_hdr.supplier.suppname + y.invoice_trans.last.invoice_hdr.client.clientname + y.invoice_trans.last.invoice_hdr.invno.to_s + y.invoice_trans.last.invtrndate.strftime('%Y%m%d') + y.invoice_trans.last.meal.mealsortseq.to_s }
The above works but is VERY slow largely because of the multiple reads to the database and I suspect the actual sort. 以上工作,但非常缓慢,主要是因为对数据库的多次读取,我怀疑实际排序。 I was wondering how I could refactor the code to use either :include
or :joins
with an :order
clause, which may help speed this up. 我想知道如何重构代码以使用:include
或:joins
与:order
子句,这可能有助于加快速度。 However I can't work out what the Rails Active record 'find' statement should be for the above. 但是我无法弄清楚Rails Active记录'find'语句应该是什么。
I am using Rails 3.2.1, Ruby 1.9.3p0 and MySQL 5.1 on Ubuntu 11.04. 我在Ubuntu 11.04上使用Rails 3.2.1,Ruby 1.9.3p0和MySQL 5.1。
What is the last transaction? 最后一笔交易是什么? Is it the one with the max ID (looking at your code, seems like it is), or the latest updated timestamp? 它是具有最大ID(查看您的代码,看起来像是)或最新更新的时间戳的那个?
Let's try to figure this out: 让我们试着解决这个问题:
AdHocBkg.joins(:adhoc_bkg_status, :invoice_trans => [ :meal, { :invoice_hdr => [ :supplier, :client ] } ]).
where("adhoc_bkg_statuses.abstatdesc='Billed' and invoice_trans.id = (select max(id) from invoice_trans as it where it.ad_hoc_bkg_id=ad_hoc_bkgs.id)").
order("suppliers.suppname desc, clients.clientname desc, invoice_hdrs.invno desc, invoice_trans.invtrndate, meals.mealsortseq desc")
I have not tested this so not sure it will work exactly like you want it to, but you can probably start from this. 我没有测试过这个,所以不确定它是否会像你想要的那样工作,但你可以从这开始。
EDIT 编辑
You can try using includes
instead of joins
if you want to access the fields you were sorting on. 如果要访问要排序的字段,可以尝试使用includes
而不是joins
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.