ruby-on-rails 如何在Rails 6中为过滤器编写深度连接查询?

qlckcl4x  于 2022-11-19  发布在  Ruby
关注(0)|答案(2)|浏览(154)

我正在尝试编写一个筛选器。我有一个订单模型,它有多个服务,每个服务都有一个分配的工作人员来执行它。我想按执行此订单中任何服务的选定员工来筛选订单。我正在尝试执行@orders = Order.joins(:services).joins(:employees).where(services: {employees: {id: params[:employee_id]}}),我知道这是不正确的。请告诉我如何提出这样的请求。

订单.rb

class Order < ApplicationRecord
  has_many :order_services, dependent: :destroy
  has_many :services, through: :order_services
end

订单服务.rb

class OrderService < ApplicationRecord
  belongs_to :order
  belongs_to :service
  belongs_to :employee

  validates :order, presence: true
  validates :service, presence: true
  validates :employee, presence: true
end

服务.rb

class Service < ApplicationRecord
  has_many :order_services, dependent: :destroy
  has_many :orders, through: :order_services
  belongs_to :employee, optional: true
end

雇员.rb

class Employee < ApplicationRecord
  has_many :order_services
  has_many :services, through: :order_services
end

我想指出的是,我的order_service模型是服务和员工的连接模型。理论上,订单和服务的连接只能在工人在场的情况下进行。+一个附加问题是,这样的交互是否不是一个坏的实践,或者将它们分为order_service和service_employee会更好?谢谢。

q3qa4bjr

q3qa4bjr1#

尝试通过服务访问雇员是一个错误,因为访问它要近得多。我们不需要通过服务调用雇员,因为该雇员记录在order_service表中,因为根据条件,我们在雇员在场的情况下具有订单和服务连接,因此我们根本不能考虑服务。

Order.joins(:order_services).where(order_services: {employee_id: params[:employee_id]})
6vl6ewon

6vl6ewon2#

我想这就是你想要的。

@orders = Order.joins(:order_services).where(order_services: { employee_id: params[:employee_id] }).distinct

相关问题