【问题标题】:How to order by multi relation table 's field?如何按多关系表的字段排序?
【发布时间】:2010-08-25 23:48:36
【问题描述】:

我需要在 rails 中生成一个收据列表,这些收据需要按项目的订单关系字段 (payment_method_meta_type.name) 进行排序。

型号:

Receipt
Deposit
PaymentMethodMetaType

在存款模式中:

class Deposit < ActiveRecord::Base

  belongs_to :payment_method_meta_type
  has_many   :receipts, :class_name=>"Receipt", :foreign_key=>"deposit_id", 
                    :dependent => :destroy
end

我已经在控制器中获得了一系列收据:

@receipts = Receipt.find(:all, :conditions => ["date BETWEEN ? AND ?", 
  @start_date, @end_date], :order => "date DESC, id DESC", 
  :limit => limit, :offset => offset)

在视图中我也可以显示 payment_method_meta_type.name

- @receipts.each do |o|
  %tr.
    .....
    %td #{o.receipt_number}
    %td #{o.deposit.payment_method_meta_type.name}
    .....

但是,当我创建收据数组的集合时,如何在控制器中按receipts.deposit.payment_method_meta_type.name 的顺序显示列表?

【问题讨论】:

    标签: sql ruby-on-rails ruby database


    【解决方案1】:

    试试这个:

    @receipts = Receipt.all(:joins => {:deposit => :payment_method_meta_type},
                  :conditions => {:date => @start_date..@end_date}, 
                  :order => "payment_method_meta_types.name ASC", 
                  :limit => limit, :offset => offset)
    

    【讨论】:

      【解决方案2】:

      thx,我终于搞定了,在查询字符串中使用'include'

      @receipts = Receipt.find(:all, :include => {:deposit => [:payment_method_meta_type] } ,:conditions => ["Receipts.business_date BETWEEN ? AND ?", @current_month_start_date, @current_month_end_date],:order => "tag_types.name , Receipts.business_date DESC",:limit => limit)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2021-01-15
        • 2011-02-02
        • 2019-04-12
        相关资源
        最近更新 更多