在我的ruby on rails应用程序中,我在模型中有一个类方法,它结合了两个记录
模型/ Client.rb
def self.get_clients
account = params[:user].current_account
account.clients + account.companies.map(&:clients).flatten
end
在控制器中我正在使用这种方法并在其上应用kaminari分页
def index
Client.get_clients(params.merge(user: current_user)).page(params[:page]).per(10).unarchived
end
我收到此错误
undefined method `page' for #<Array:0xb6743220>
如何将此数组转换为活动记录?或者是否有其他方法来组合这些记录?
答案 0 :(得分:1)
试试这个:
class Client < ActiveRecord::Base
scope :for_account, ->( account ){
companies_account_id = Company.arel_table[:account_id]
accounts_id = Account.arel_table[:id]
# 'uniq' is ActiveRecord's "SELECT DISTINCT"
# the where clause is Arel for "companies.account_id = ? OR accounts.id = ?"
uniq
.joins( :company, :account )
.where(
companies_account_id.eq( account.id ).or( accounts_id.eq(account.id) )
)
}
end
然后在你的控制器中:
@clients = Client.for_account( current_user.current_account )