How to eager load the data
i have three models called City, User, Bank
so i need to eager load the data to avoid N+1 Queries
here in my method of city.rb
def update_data(activity = false) # Used in delayed Job# Filtering the Users
#here i need to filter the users based on the activity#if the activity is true then i need to fetch all the users of the cityelse i need to fetch the users who belongs to the city where the bank of the user has enabled_banking flag false and those user who dont have any bankso i have written a query like filtered_users = activity ? users : users.left_joins(:banks).where("(banks.enabled_banking = ?) OR (banks.id IS NULL)", false)
#then
filtered_users.find_in_batches do |city_users| city_users.each do |user| user.format_and_process endend
end
but i need to avoid n+1 queries in both cases, fetching all the users and also when i append the left join to fetch the records.
How to achieve this
previously i updated like
users.includes(:city, :bank)
then
filtered_users = activity ? users : users.left_joins(:banks).where("(banks.enabled_banking = ?) OR (banks.id IS NULL)", false).references(:banks)but this will not the optimzed way to fetch the records.How we can achieve this expected behaviour?