Rails ActiveRecord has_one和belongs_to重新加载关联

时间:2014-03-14 15:29:53

标签: ruby-on-rails activerecord belongs-to has-one

我有四个模特

class Votation
  belongs_to :quorum

  def calc
    return self.quorum.calc
  end

end

class Quorum
  has_one :votation
  ...
end

class NewQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_a
  end
end

class OldQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_b
  end
end

我已将投票加载到@votation对象中并急切加载相关的仲裁。

问题在于,当我调用@votation.calc时,ActiveRecord会执行SQL select以在必须执行self.votation.attribute_a时再次加载投票。

SELECT "votations".* FROM "votations" WHERE "votations"."quorum_id" = $1

如何避免执行此选择?

1 个答案:

答案 0 :(得分:0)

指定关联时可以使用:inverse_of选项来阻止执行另一个select语句。

所以你的模型看起来像:

 class Votation
   belongs_to :quorum, inverse_of: :votation
 end

 class Quorum
   has_one :votation, inverse_of: :quorum
 end

参考:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to