Alex Zakruzhetskyi
Alex Zakruzhetskyi

Reputation: 1433

How to reorder results after serchkick finds a proper result?

When I do in rails console this: posts = Post.active.search('lorem').records it gives me this: Post Load (0.9ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` IN (3, 1, 2) LIMIT 11 But when I do posts.pluck(:id) the result is: [1, 2, 3]. So, as you can see, the order is not the same, as it is in a query, it should be [3, 1, 2]. How can I reorder the result, so it will be [3, 1, 2]? Thanks.

Upvotes: 3

Views: 55

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

Here is a raw MySQL query which will generate the output you expect:

SELECT *
FROM posts
WHERE
    id IN (3, 1, 2)
ORDER BY
    FIELD(id, 3, 1, 2)
LIMIT 11

I have little knowledge about ActiveRecord but I would expect that you would need to use raw SQL for the above ORDER BY clause, and possibly for the entire query. One option here would be to run the entire raw query:

sql = "SELECT * FROM posts ... ORDER BY FIELD(id, 3, 1, 2) LIMIT 11"
records_array = ActiveRecord::Base.connection.execute(sql)

Upvotes: 2

Related Questions