[英]Rails ActiveRecord has_one and belongs_to reloading association
I have four models 我有四个型号
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
I have loaded the votation into a @votation
object and eager loaded the associated Quorum. 我已经将投票加载到@votation
对象中,并渴望加载相关的Quorum。
The problem is that when I call @votation.calc
, ActiveRecord execute a SQL select to load the votation again when it has to execute self.votation.attribute_a
for example. 问题是,当我调用@votation.calc
,ActiveRecord执行SQL选择以再次加载self.votation.attribute_a
(例如必须执行self.votation.attribute_a
。
SELECT "votations".* FROM "votations" WHERE "votations"."quorum_id" = $1
how can I avoid this select from being executed? 如何避免执行此选择?
You can use the :inverse_of
option when specifying the association to prevent another select statement from being executed. 指定关联时,可以使用:inverse_of
选项,以防止执行另一个select语句。
So your models would look like: 因此您的模型如下所示:
class Votation
belongs_to :quorum, inverse_of: :votation
end
class Quorum
has_one :votation, inverse_of: :quorum
end
Reference: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to 参考: http : //apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.