Ruby on rails Rails按日期排序查询
我的付款、发票和交易模型设置如下:Ruby on rails Rails按日期排序查询,ruby-on-rails,ruby,polymorphic-associations,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 :transactio
# 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
#transaction.rb
类事务
在我的客户展示模板中,我将查找属于请求客户的所有交易。我想按它们所属的发票或付款日期对交易进行排序。实现这一目标的最佳方式是什么
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
class CustomerController
如果交易总是与付款或发票一起创建,则可以使用交易表上的创建时间戳。但是,如果没有,为了避免事务模型明确知道它可以属于哪些模型,一个好的选择是在事务表上创建另一个datetime列,并使用关联对象中最相关的datetime进行更新。可以使用范围
您应该能够执行以下操作:
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
类事务{includes(:transactionable)}
范围:按付款日期订购,->{
#这可能有效,也可能无效,您可能需要指定一个has\u many
#与付款的关系,或者做更多的事情来让加入工作
联接(Payment.arel_表)。合并(Payment.descending)
}
范围:按发票日期订购,->{
#这可能有效,也可能无效,您可能需要指定一个has\u many
#与发票的关系,或执行更多操作以使连接生效
联接(Invoice.arel_表)。合并(Invoice.descending)
}
结束
类付款{订单(arel_表[:付款日期].desc)}
结束
类发票{订单(arel_表[:发票日期].desc)}
结束
我同意此解决方案,相关的交易时间
应记录在交易
上,与发票
或付款
的任何时间分开。这是可行的,但如果我想按付款或发票金额等其他值对交易进行排序,我还必须将这些列添加到事务表中。这似乎是多余的。