Rails查询通过子类将子类与父类连接在一起

问题描述 投票:0回答:1

我有以下课程

class Order
   has_many :order_issues, through: :order_deliveries, inverse_of: :order
end

class OrderDelivery
   has_many :order_issues, as: :issuable, inverse_of: :order_delivery
end

class OrderIssue
   belongs_to :order, inverse_of: :order_issues
end

当我尝试

Order.joins(:order_issues).to_sql 


SELECT * 
FROM orders 
INNER JOIN order_deliveries 
   ON order_deliveries.order_id = orders.id 
INNER JOIN order_issues 
   ON order_issues.issuable_id = order_deliveries.id 
      AND order_issues.issuable_type = 'OrderDelivery' 

但是,当我尝试时

OrderIssue.joins(:order).to_sql

SELECT order_issues.id 
FROM order_issues 
INNER JOIN orders 
    ON orders.id = order_issues.order_id

为什么不同?是否可以获取相同类型的联接但获得OrderIssue活动记录?

ruby-on-rails activerecord rails-activerecord has-and-belongs-to-many
1个回答
0
投票

inverse_of仅用于避免重复检索相同的记录;它不会更改ActiveRecord关系解析的行为。

在这种情况下,不使用has_many :order_issues选项设置:through似乎是正确的用法,因为OrderIssue直接是belongs_to :order,因此可以为您提供所需的查询。 OrderDelivery也应相应更新。

class Order
  has_many :order_issues
  has_many :order_deliveries
end

class OrderDelivery
  belongs_to :order
  has_many :order_issues, through: :order
end

class OrderIssue
  belongs_to :order
  has_many :order_deliveries, through: :order
end
© www.soinside.com 2019 - 2024. All rights reserved.