如何在多态场景中获取关联的记录

时间:2019-07-11 13:29:34

标签: ruby-on-rails ruby-on-rails-5.2

我有类似的情况

class Manager
  has_many :employees
  has_many :transactions, as: :transactable
end

class Employee
  belongs_to :manager
  has_many :transactions, as: :transactable
end

class Transaction
  belongs_to :transactable, polymorphic: true
end

是否有更好的方法来获取Manager或/和他的employees进行的所有交易?任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

class Transaction

  def self.belonging_transactions(manager)
    where(
      "(transactable_type = 'Manager' AND transactable_id = ?) OR (transactable_type = 'Employee' AND transactable_id IN ?)",
      manager.id,
      manager.employees.ids
    )
  end

end

您可以通过以下方式获取所有经理及其雇员的交易

Transaction.belonging_transactions(manager) # here manager is Manager class object

可以通过添加(使用+)两个where查询来获得结果,但这将是Array而不是ActiveRecord::Relation

答案 1 :(得分:-1)

您可以为Transaction及其Manager制作的employees定义自定义范围:

class Transaction
  scope :belonging_transactions, ->(manager) do
    where(transactable_type: "Manager", transactable_id: manager.id)
      .or(transactable_type: "Employee", transactable_id: manager.employees.ids)
  end
end

或者,您可以定义一个执行相同操作的类方法:

class Transaction

  def self.belonging_transactions(manager)
    where(transactable_type: "Manager", transactable_id: manager.id)
      .or(transactable_type: "Employee", transactable_id: manager.employees.ids)
  end

end