Reputation: 709
I have these models:
class Folder < ApplicationRecord
has_many :files, -> { reorder_descending }, dependent: :destroy
has_many :not_deleted_files, -> { not_deleted.reorder_descending }, class_name: 'File'
end
class File < ApplicationRecord
belongs_to :folder
scope :not_deleted, -> { where('deleted_at IS NULL ') }
scope :reorder_ascending, -> { reorder('enactment_date ASC, finding_date ASC, id ASC') }
scope :reorder_descending, -> { reorder('enactment_date DESC, finding_date DESC, id DESC') }
def not_deleted_files
folder.not_deleted_files
end
end
Now i have a folder and I iterate over all it's files. In the File class I have a lot of methods that are using the not_deleted_files method. Every time this method is used, a new query is fired. Even though they all have the same parent (Folder).
Also the queries are cached, I think there should be a way to prevent them at all.
Upvotes: 0
Views: 267
Reputation: 1227
You can use inverse_of
as Rails can optimize object loading so parent_object
and child_object.parent
will reference the same object in memory, instead of loading another copy of the same record.
I am glad it helped. :)
Upvotes: 1