我有这样的付款、发票和交易模型设置:
# 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
最佳答案
范围可能是可能的。
您应该能够执行以下操作:
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
关于ruby-on-rails - Rails 按日期排序查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464984/