我有以下课程
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活动记录?
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