Answer the question
In order to leave comments, you need to log in
How to fix sorting of received data from DB?
There is a request like this:
posts_and_images = current_user.posts_and_images.select('DISTINCT ON (post_id) post_id, id, user_id, image_id, position').order(:post_id, position: :desc)
.order(position: :desc, post_id: :desc)
PG::InvalidColumnReference: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1
Answer the question
In order to leave comments, you need to log in
First of all, you need to understand what you generally want to receive from the request? Formulate, please, in simple words and sound.
In your query, without sorting, the database cannot figure out how to select unique post_ids. By adding this field to the ORDER BY, the query starts to pass, however, the following position qualifications are discarded. But it also makes sense! After all, sorting is specified only when the same values go to the previous field, and here all the values \u200b\u200bare different in the post_id field (due to distinct).
Hence you need to use nested queries. First we find unique posts, and then we sort them by position using an external select.
Isn't there an error in the code? For :post_id, you need to write :desc or :asc, right?
Or try the following options:
Thing.all.order("updated_at DESC, price ASC")
Model.order(foo: :asc, bar: :desc)
Model.order(:updated_at).order(:price)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question