Rails按日期排序查询

时间:2016-04-07 01:11:57

标签: ruby-on-rails ruby polymorphic-associations

我的付款,发票和交易模型设置如下:

# transaction.rb
class Transaction < ActiveRecord::Base
  belongs_to :customer
  belongs_to :transactionable, polymorphic: true
end

# payment.rb
class Payment < ActiveRecord::Base
  belongs_to :customer
  has_many :transactions, as: :transactionable
end

# invoice.rb
class Invoice < ActiveRecord::Base
  belongs_to :customer
  has_many :transactions, as: :transactionable
end

在我的客户展示模板中,我找到了属于所请求客户的所有交易。我想按照他们所属的发票或付款日期对交易进行排序。实现这一目标的最佳方法是什么?

class CustomersController < ApplicationController
  def show
    @customer = Customer.find(params[:id])

    # I want the transactions sorted by the date of the Invoice or Payment they belong to 
    @transactions = Transaction.where(customer: @customer)
  end
end

2 个答案:

答案 0 :(得分:2)

可能有范围。

您应该可以执行以下操作:

transactions = Transaction.all
transactions = transactions.order_by_payment_date
transactions = transactions.order_by_invoice_date
transactions = transactions.includes_transactionable

transactions.each do |transaction|
  # do what you want with the transaction and transactable
end

希望这段代码能够正常运行:

class Transaction < ActiveRecord::Base
  belongs_to :customer
  belongs_to :transactionable, polymorphic: true

  scope :includes_transactionable, -> { includes(:transactionable) }

  scope :order_by_payment_date, -> {
    # This may or may not work, you may need to specify a has_many 
    # relationship to Payment, or do more to get the join to work
    joins(Payment.arel_table).merge( Payment.descending )
  }

  scope :order_by_invoice_date, -> {
    # This may or may not work, you may need to specify a has_many 
    # relationship to Invoice, or do more to get the join to work
    joins(Invoice.arel_table).merge( Invoice.descending )
  }
end

class Payment < ActiveRecord::Base
  belongs_to :customer
  has_many :transactions, as: :transactionable

  scope :descending, -> { order(arel_table[:payment_date].desc) }
end

class Invoice < ActiveRecord::Base
  belongs_to :customer
  has_many :transactions, as: :transactionable

  scope :descending, -> { order(arel_table[:invoice_date].desc) }
end

答案 1 :(得分:1)

如果始终在付款或发票旁边创建交易,您可以在交易表上使用created_at时间戳。但是,如果没有,为了防止事务模型明确知道它可以属于哪个模型,一个好的选择是在事务表上创建另一个datetime列,并使用与日期最相关的任何日期时间更新它。相关对象。