我将从测试开始,以显示所需的功能:
item = LineItem.new
order = Order.new
OrderLineItem.new(order: order, line_item: item)
related_order = item.orders.first
expect(related_order).to eq order
评估为:
expected: #<Order ....>
got: nil
以上3个模型的相关内容如下:
class LineItem < ActiveRecord::Base
has_many :order_line_items, as: :line_item, inverse_of: :line_item
has_many :orders,
through: :order_line_items,
source: :order,
inverse_of: :line_items
end
class OrderLineItem < ActiveRecord::Base
belongs_to :order, inverse_of: :order_line_items
belongs_to :line_item,
polymorphic: true, inverse_of: :order_line_items
end
class Order < ActiveRecord::Base
has_many :line_items,
through: :order_line_items,
source: :line_item,
inverse_of: :orders
has_many :order_line_items, dependent: :destroy, inverse_of: :order
end
我可以通过保存所有内容并在我的期望行之前调用item.reload
来完成所有工作。但是不是inverse_of
应该挂掉所有这些吗?
也许我对预先保存的对象期待inverse_of
太多了?
答案 0 :(得分:2)
不,inverse_of
不能与has_many :through
参见&#34;双向关联&#34; ActiveRecords协会文档的一部分:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods。
有一些限制:inverse_of支持:
- 不适用于:通过协会。
- 不适用于:多态关联。
- 对于belongs_to关联has_many反向关联被忽略。
另请参阅:ActiveRecord :inverse_of does not work on has_many :through on the join model on create