Anish
Anish

Reputation: 558

Rails method call on active record relation

I have what to call a method in model from controller, where controller has active record relation object

like

@paid_drivers = DriverInvoice.where(driver_id: current_affilate_company.drivers.pluck(:id)) 

where I got

>     <ActiveRecord::Relation [#<DriverInvoice id: 1, driver_id: 13, total_reservations: 2, total_from_reservations: 20.0, pay: 20.5,
> discount_amount: 0.0, other_amount: 0.5, tax: 0.0, created_at:
> "2016-02-03 05:14:56", updated_at: "2016-02-03 05:14:56",
> payment_type: 1, is_other_addition: true, is_tax_per: true, tax_value:
> nil>, #<DriverInvoice id: 2, driver_id: 56, total_reservations: 3,
> total_from_reservations: 452.0, pay: 452.0, discount_amount: 0.0,
> other_amount: 0.0, tax: 0.0, created_at: "2016-02-03 05:15:36",
> updated_at: "2016-02-03 05:15:36", payment_type: 1, is_other_addition:
> true, is_tax_per: true, tax_value: nil>]>

now on that obj. I want a method call @paid_drivers = @paid_drivers.search_paid_driver()

and in my model

def self.search_paid_driver()
 raise self.inspect
end

That give only table fields

like

DriverInvoice(id: integer, driver_id: integer, total_reservations: integer, total_from_reservations: float, pay: float, discount_amount: float, other_amount: float, tax: float, created_at: datetime, updated_at: datetime, payment_type: integer, is_other_addition: boolean, is_tax_per: boolean, tax_value: float)

I want all recoreds of @paid_drivers so I can process them further in my model.

How can I do that pls help.

Upvotes: 0

Views: 2301

Answers (2)

Long Nguyen
Long Nguyen

Reputation: 373

You should use active record scope for yo

class DriverInvoice
  scope :for_company, -> (company) { where(driver_id: current_affilate_company.drivers.pluck(:id))}
end

@paid_drivers = DriverInvoice.for_company(current_affilate_company) 

Then you can use other filters by defining other scopes or using where chain

Upvotes: 2

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

self inside self.search_paid_driver() is the DriverInvoice class, not the ActiveRelation instance. So, what you got as output is right.

I would suggest using a scope for this kind of query.

Still if you want to achieve same with class method, it should be something like this:

def self.search_paid_driver(current_affiliate_company)
    .where(driver_id: current_affiliate_company.drivers.pluck(:id))
end

Or if you can manage current_affiliate_company from inside the class, you can omit the method param.

Upvotes: 2

Related Questions