ruby-on-rails - Rails 按日期排序查询

标签 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

最佳答案

范围可能是可能的。

您应该能够执行以下操作:

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/

相关文章:

ruby-on-rails - rails 3 : validates_presence_of validation errors on default value and in associated model

ruby-on-rails - 添加 www.总体设计电子邮件或 Rails?

c++ - 具有类型转换的多态复制构造函数

ruby-on-rails - rails has_one 一个 has_many 关联

javascript - 无法点击我的 Angular-rails Reddit 克隆上的赞成票

ruby-on-rails - 使用自定义键扩展 `find_by`

ruby - Ruby 中的自定义排序

ruby-on-rails - Rails 中多类型注册的多态关联

ruby-on-rails - 如何拥有多个版本的 Ruby 和 Rails,以及它们在 Windows 上的组合?

ruby glade/gtkbuilder 示例?