我有四个模特
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
如何避免执行此选择?
答案 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