[英]Rails ActiveRecord has_one and belongs_to reloading association
我有四个型号
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
对象中,并渴望加载相关的Quorum。
问题是,当我调用@votation.calc
,ActiveRecord执行SQL选择以再次加载self.votation.attribute_a
(例如必须执行self.votation.attribute_a
。
SELECT "votations".* FROM "votations" WHERE "votations"."quorum_id" = $1
如何避免执行此选择?
指定关联时,可以使用: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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.