【问题标题】:Rails method call on active record relationRails方法调用活动记录关系
【发布时间】:2016-02-03 19:08:46
【问题描述】:

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

喜欢

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

现在在那个 obj 上。我想要一个方法调用 @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:浮动,支付:浮动,折扣金额: 浮动,其他金额:浮动,税:浮动,created_at:日期时间, updated_at:日期时间,payment_type:整数,is_other_addition: boolean, is_tax_per: boolean, tax_value: float)

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

请问我该怎么做。

【问题讨论】:

  • 是否要将所有付费驱动程序加载到内存中?只需@paid_drivers = DriverInvoice.where(driver_id: current_affilate_company.drivers.pluck(:id)).all。但是你应该让它延迟加载
  • @LongNuyen 你能详细说明你的答案吗
  • 但是你想要什么?
  • 我想将更多过滤器放在我作为@paid_driver 获得的对象上
  • 啊,你可以用scope。这是文档api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/…

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


【解决方案1】:

你应该使用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) 

然后你可以通过定义其他scopes或者使用where链来使用其他过滤器

【讨论】:

    【解决方案2】:

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

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

    如果你想用类方法达到同样的效果,它应该是这样的:

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

    或者如果你可以在类内部管理current_affiliate_company,你可以省略方法参数。

    【讨论】:

    • 如果我将 @paid_drivers 从控制器传递给模型中的 search_paid_driver 方法,我的意思是这不是一种轨道方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多