Rails 使用 will_paginate 组合查询结果
Rails use will_paginate with combined query results
在我的应用程序中,我有一个包含许多付款和发票的客户模型。
# 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])
完成此任务的最佳方法是什么?
最好的方法是创建第三个 Table 具有多态关联的事务作为可事务的。并对交易进行分页。
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
其他对两者都分页或使用分页数组都不好的方法。
在我的应用程序中,我有一个包含许多付款和发票的客户模型。
# 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])
完成此任务的最佳方法是什么?
最好的方法是创建第三个 Table 具有多态关联的事务作为可事务的。并对交易进行分页。
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
其他对两者都分页或使用分页数组都不好的方法。