[英]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.