2016-04-07 3 views
2

によって私はこのような支払い、請求書、およびトランザクションモデルを設定している:私の顧客でRailsは、ソートクエリの日付

# 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 

答えて

1

、あなたは、トランザクションテーブルにcreated_atタイムスタンプを使用することができます。ただし、トランザクションモデルで特定のモデルを特定できないようにするには、トランザクションテーブルに別の日時列を作成し、その中で最も関連性の高い日時を更新することをお勧めします関連付けられたオブジェクト。

+0

を、私はこの解決策に同意し、関連する 'トランザクションtime'が上に記録されなければなりません「取引」は、「請求書」または「支払」の任意の時刻とは別個である。 – br3nt

+0

これはうまくいくはずですが、支払いや請求書の金額など他の値で取引を並べ替える場合は、これらの列を取引テーブルに追加する必要があります。これは冗長なようです。 – James

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 
関連する問題