Rails方法调用活动记录关系

时间:2016-02-03 06:42:39

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我有从控制器调用模型中的方法,其中控制器具有活动记录关系对象

喜欢

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

我得到的地方

>     <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>]>

现在就在那个对象上。我想要一个方法调用     @paid_drivers = @ paid_drivers.search_paid_driver()

在我的模特中

def self.search_paid_driver()
 raise self.inspect
end

仅提供表格字段

喜欢

  

DriverInvoice(id:integer,driver_id:integer,total_reservations:   整数,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)

我想要@paid_drivers的所有记录,以便我可以在我的模型中进一步处理它们。

我该怎么做才能帮忙。

2 个答案:

答案 0 :(得分:2)

self内的{p> self.search_paid_driver()DriverInvoice类,而不是ActiveRelation实例。所以,你得到的输出是正确的。

我建议使用范围进行此类查询。

如果你想用类方法实现相同,它应该是这样的:

<VirtualHost 127.0.0.1:80>
DocumentRoot "D:/xampp/htdocs/bonfire"
ServerName 127.0.0.1
ServerAlias bonfire.dev
</VirtualHost>

或者,如果您可以从课程内部管理def self.search_paid_driver(current_affiliate_company) .where(driver_id: current_affiliate_company.drivers.pluck(:id)) end ,则可以省略方法参数。

答案 1 :(得分:2)

您应该使用active record scope作为哟

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

@paid_drivers = DriverInvoice.for_company(current_affilate_company) 

然后,您可以通过定义其他scope或使用where

来使用其他过滤器