I am trying to speed up a Rails query that is consuming a lot of time I reload the page.
I have this in the rails view:
<% if current_account.subscribed? and current_account.subscription.plan.id == 2 %>
<div class="flex items-center bg-blue-100 rounded-lg px-2 mb-2 shadow-lg data-controller="tooltip" data-tippy-content="Clases reservadas este mes" data-tippy-delay="0" data-tippy-arrow="true" data-tippy-size="regular" data-tippy-animation="fade">
<div class="mr-2 flex-shrink-0 text-3xl md:text-2xl">
📆
</div>
<div>
<p class="text-3xl md:text-2xl font-bold">
<%= @lessons_basic_count %>
</p>
</div>
</div>
And this is the query I run on the controller:
@lessons_basic_count = @mylessons_lessons.where(datetime: Time.at((current_account.subscription.latest_payment.created if current_account.subscription.latest_payment).to_i)..(Date.current + 30.days)).size
It's a query that looks on the table mylessons which contains lessons a user has booked in the actual period of their subscription.
Thanks.
EXPLAIN <SQL here>what does it show? Maybe you need an index for a column or set of columns on this table.EXPLAIN for: SELECT "lessons".* FROM "lessons" INNER JOIN "mylessons" ON "lessons"."id" = "mylessons"."lesson_id" WHERE "mylessons"."user_id" = $1 AND "lessons"."datetime" BETWEEN $2 AND $3 [["user_id", 18], ["datetime", "2021-06-28 12:50:20"], ["datetime", "2021-07-28"]] QUERY PLANThis is the SQL query without the .size at the endlatest_payment? The name suggests that a subscriptionhas_many :payments. If you determine the latest payment by loading all payments instead of using a query things could be slowed down considerably.