2

我有这样的关联模型:

class Batch
  has_many :logs

class Log
  belongs_to :batch

我正在使用包含来加载带有日志的批次:

b = Batch.includes(:logs)

哪个运行 2 按预期选择(批次和日志)。

然后我做

b.first.logs.first.batch

这会触发对批次的另一个选择,即使它们已经实际加载。我想通过执行 include(:logs => :batch) 来“修复”它,但我仍然认为这里有问题,因为相同的批次被加载了两次。是什么赋予了?

4

1 回答 1

1

You can fix this with the :inverse_of setting, which lets ActiveRecord know that the two associations are the inverse of each other.

class Batch
  has_many :logs, :inverse_of => :batch
end

class Log
  belongs_to :batch, :inverse_of => :logs
end
于 2012-12-28T21:38:58.203 回答