强制first_or_initialize分配关联?

时间:2016-12-15 07:33:18

标签: ruby-on-rails activerecord

我有一个类别关联的产品型号,如下所示:

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

1 个答案:

答案 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