1

I have some parameters in URL that represents IDs. On this page, I am printing out a list of articles - usually between 50 and 70.

In the URL are IDs - say - in this format: website.com/mark/articles/10/12/13/20 (IDs of articles: 10, 12, 13, 20).

I would save these IDs into an array and while printing out all Mark's articles on the page, I would need to sort the articles the way that articles with IDs 10, 12, 13 and 20 would be on top of the list.

How to achieve something like this?

2
  • Are you only displaying those four articles? If not, what would the secondary sort key be? Commented Dec 2, 2014 at 22:40
  • I am displaying all articles, and those 4 on top of them. Commented Dec 2, 2014 at 23:32

2 Answers 2

2

For a SQL solution, check mu's answer. Using Ruby:

articles = Article.where(id: ids).index_by(&:id).values_at(*ids) +
  Article.where.not(id: ids)

Of course, a SQL solution is nicer if you need a Relation and not an Array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @tokland for the answer, but this displays only articles with the specified IDs in the URL. I'd need to display all articles and sort them by those in the URL (the ones in URL would be on the beginning of the list of articles)
1

There are two ways to do this. Plain ruby or SQL.

The plain ruby version is probably easier to understand and also not vulnerable to possible SQL injection:

article_ids_on_top = [10, 12, 13, 20]
articles = Article.all
top_articles = articles.select{|article| article_ids_on_top.include?(article.id) }
bottom_raticles = articles.reject{|article| article_ids_on_top.include?(article.id) }

@articles = top_articles + bottom_articles

SQL version:

article_ids_on_top = [10, 12, 13, 20]
@articles = Article.order("FIELD(id, [#{article_ids_on_top.join(',')})")

2 Comments

Isn't FIELD a MySQL-ism?
@Milan thanks for the answer. When I try the SQL version, it returns an error about using the brackets [ ] incorrectly, if I use it without the brackets, the error is gone, but the data are not sorted properly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.