如何遍历关联

时间:2019-07-27 12:18:36

标签: ruby-on-rails ruby ruby-on-rails-5 activeadmin

我发现遍历Active Admin中的关联非常棘手。

在我的应用程序中,我有一个SupportSession出现在发票上。通过与SupportAllocation的关联,我可以遍历整个链以在SupportSession上对SupportRate收费。我可以在计算发票价值时使用这些费率。

我的模特是:

class Invoice < ApplicationRecord
  has_one :support_session

class SupportSession < ApplicationRecord
  belongs_to :invoice, optional: true
  belongs_to :support_allocation

class SupportAllocation < ApplicationRecord
  has_many :support_sessions
  has_many :support_rates

class SupportRate < ApplicationRecord
  belongs_to :support_allocation

我已经为发票创建了一个Active Admin资源,我想在其中进行一些计算:

ActiveAdmin.register Invoice do

  index do
    selectable_column

    column 'Reference', :reference, :sortable => 'invoices.reference'
    column 'Raised', :created_at, :sortable => 'invoices.created_at' do |invoice|
      invoice.created_at.strftime('%Y-%m-%d')
    end
    column 'Due by', :due_by, :sortable => 'invoices.due_by'

    column :value do |invoice|
      # The next line retrieves an array of SupportRate(s) associated with this SupportSession on this invoice
      invoice.support_session.support_allocation.support_rates.each do |support_rate|

      # If the current SupportSession's support_type matches the SupportRate's support_type
        if support_rate.support_type == invoice.support_session.support_type
          # Do some calculations based on the support_rate.price attribute, plus some other bits I've omitted
        end
      end
      # The next line returns the correct price but obviously it's too clumsy and doesn't do the match on support_type
      # invoice.support_session.support_allocation.support_rates[0].price
    end

    actions
  end

end 

我可以看到正在正确检索数据。我也可以看到它是一个数组。但是如果我尝试做任何事情,例如在“如果”条件下打印出support_rate.price,我就可以得到(例如,对于第一条记录):

[#<SupportRate id: 3, support_type: "mentoring", price: 0.3e2, support_allocation_id: 2>, #<SupportRate id: 13, support_type: "study_skills", price: 0.45e2, support_allocation_id: 2>]

在此特定示例中,匹配的support_type为'study_skills'-我需要使用该support_rate的价格进行计算。

我想象解决方案在于像我尝试的那样在数组中进行某种循环或匹配速率? Active Admin似乎并不喜欢它。

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我通过在可用的关联上调用查询来解决此问题(find_by方法):

Invoice.calculate_value(invoice.support_session.support_allocation.support_rates.find_by(support_type: invoice.support_session.support_type).price

我记得一个关联是一个对象,因此继承了所有可用的常规查询方法。

为了进行必要的计算,我刚刚创建了一个自定义函数,将值交给该函数,然后返回一个计算出的值:

column :value do |invoice|
      Invoice.calculate_value(invoice.support_session.support_allocation.support_rates.find_by(support_type: invoice.support_session.support_type).price, invoice.support_session.rounded_duration_mins)
    end