我有一个类别关联的产品型号,如下所示:
class Product < ApplicationRecord
belongs_to :category
end
然后,在方法中,我有:
c = Category.find(1) #a preloaded category.
p = Product
.where(
category: c,
color: "red"
)
.first_or_initialize
p.category.name #triggers a query to load category
该类别已加载,并已传递到where()
,但当我尝试通过p
访问时,它会运行另一个查询。
我可以避免这样的额外查询,但是有没有办法在不将c
传递到p
两次的情况下完成相同的操作?
c = Category.find(1) #a preloaded category.
p = Product
.where(
category: c,
color: "red"
)
.first_or_initialize
p.category = c #manual assignment, no query
p.category.name #now this doesn't trigger another query
答案 0 :(得分:1)
在声明关联时使用inverse_of
选项
class Category < ActiveRecord::Base
has_many :products, inverse_of: :category
end
class Product < ActiveRecord::Base
belongs_to :category, inverse_of: :products
end