在我的应用程序中,我有一个客户模型,其中包含许多付款和发票。
# 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进行分页。这样做并不起作用:
@transactions.paginate(page: params[:page])
实现这一目标的最佳方法是什么?
答案 0 :(得分: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
其他不利于分页或使用paginate数组的方法。