2016-04-04 45 views
4

在我的應用程序中,我有一個客戶模型,其中有很多付款和發票。Rails使用will_paginate並結合查詢結果

# customer.rb 
class Customer < ActiveRecord::Base 
    has_many :payments 
    has_many :invoices 
end 

# payment.rb 
class Payment < ActiveRecord::Base 
    belongs_to :customer 
end 

# invoice.rb 
class Invoice < ActiveRecord::Base 
    belongs_to :customer 
end 

在客戶展示模板中,我將所有發票和付款組合在一起,並將它們存儲在@transactions實例變量中。

class CustomersController < ApplicationController 
    def show 
    @customer = Customer.find(params[:id]) 
    payments = Payment.where(customer: @customer) 
    invoices = Invoice.where(customer: @customer) 
    @transactions = payments + invoices 
    end 

我想使用will_paginate分頁@交易。這樣做不起作用:

@transactions.paginate(page: params[:page]) 

完成此操作的最佳方法是什麼?

+0

這個答案將解決你的問題http://stackoverflow.com/questions/4352895/ruby-on-rails-will-paginate-an-array – Thorin

回答

4

最好的方法是創建第三個具有多態關聯的交易表作爲可交易的。並對事務進行分頁。

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

先學會態關聯

這是不好的進行分頁雙方或使用分頁陣列
class Transaction < ActiveRecord::Base 
    belongs_to :transactionable, polymorphic: true 
end 

class Invoice < ActiveRecord::Base 
    has_many :transactions, as: :transactionable 
end 

class Payment < ActiveRecord::Base 
    has_many :transactions, as: :transactionable 
end 

其他方式。

+0

我是新來的鐵軌。你可以提供資源,我可以學習如何做到這一點。 – James

+0

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations –