4

In my application I have a customers model that has many payments and invoices.

# 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

In the customers show template I am combining all Invoices and Payments and storing them in the @transactions instance variable.

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

I want to paginate @transactions using will_paginate. Doing this doesn't work:

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

What is the best way to accomplish this?

James
  • 1,873
  • 3
  • 22
  • 28
  • This Answer will solve your problem http://stackoverflow.com/questions/4352895/ruby-on-rails-will-paginate-an-array – Thorin Apr 04 '16 at 13:33

1 Answers1

4

Best way is to create a third Table of Transactions with polymorphic association as transactionable. And paginate over transactions.

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

First Learn polymorphic association

 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

Other way which is not good to paginate both or use paginate array.

z.shan
  • 341
  • 1
  • 2
  • 13