Home>
Error message

In the following code, if the order is removed, the n + 1 problem will not occur, but in this state, the n + 1 problem will occur.
Is the usage of order wrong?

Applicable source code
clips = User
   .includes ({clips: {restaurant: [: restaurant_pictures,: category, {near_stations:: station}]}})
   .find (user_id) .clips.order (: created_at)
  • Answer # 1

    .orderis a method that appliesORDER BYat the database level, so the relation will be recreated for that.

    I feel that it is better to subtractClipdirectly than to take it fromUser.clips.

    clips = Clip.includes (restaurant: omitted)
                .where (user_id: user_id)
                .order (: created_at)

  • Answer # 2

    Sorry, it was a tonchin question.
    Self-solve.

  • Answer # 3

    It seems that it can be solved by adding .includes () to order, but what to specify is unknown because the relation of the table is not well understood.
    There seems to be a library to check, so how about being introduced?
    Rails library introduction: "bullet" to detect N + 1 problems
    * Since the article is old, it may be replaced with something new.

Related articles