我有类似的情况
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
进行的所有交易?任何帮助,将不胜感激。谢谢!
答案 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