For example, there are users and posts that these users create, how to get all the posts sorted, say, by the date the user was created?

Did this way:

Post.all.includes(:user).order('users.created_at ASC') 

But on the production server, a similar request resets on timeout, and in general it works unacceptably long. How to do without includes?

Update

Specifically, my query looks like this (so the joins already exist):

 addresses = Address.where(services:{active: true}).joins(:service).joins(:district => :city).joins(:district).includes(:jobs).includes(:addresses_car_models, :car_models) addresses = addresses.distinct 

when adding .order('services.search_priority DESC') I get the error:

 PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list LINE 1: ...s"."active" = 't' AND "cities"."id" = 1 ORDER BY services.s... 
  • 2
    Maybe try joins? - MAXOPKA
  • And look at the output .explain . - D-side

1 answer 1

Zaapdeytil question and immediately found the answer:

I added .select("addresses.*, services.search_priority") to the main query and everything began to work as it should.