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.
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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.