1

In my ruby on rails application i have a class method in model which is combining two records

models/Client.rb

def self.get_clients
 account = params[:user].current_account
 account.clients + account.companies.map(&:clients).flatten
end

In controller i am using this method and applying kaminari paging on it

   def index
    Client.get_clients(params.merge(user: current_user)).page(params[:page]).per(10).unarchived
   end

I am getting this error

undefined method `page' for #<Array:0xb6743220>

How can i convert this array to an active record ? or is there some other way to combine these records?

4

1 回答 1

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 )
于 2013-06-05T12:21:23.587 回答