I am using Ruby on Rails 3.2.9 and MySQL. I have an Article model with a user_id attribute (this attribute represents the foreign key – id – for associated author users) and I would like to retrieve articles ordering those “for” a given author. That is, given I have following records:
<#Article id: 1, title: "Title 1", user_id: 1>
<#Article id: 2, title: "Title 2", user_id: 2>
<#Article id: 3, title: "Title 3", user_id: 1>
<#Article id: 4, title: "Title 4", user_id: 3>
<#Article id: 5, title: "Title 5", user_id: 1>
...
<#Article id: N, title: "Title N", user_id: M>
When I look for articles ordered “for” the author with id 1 (user_id = 1) then the returning articles should be ordered as-like the following:
<#Article id: 1, title: "Title 1", user_id: 1>
<#Article id: 3, title: "Title 3", user_id: 1>
<#Article id: 5, title: "Title 5", user_id: 1>
<#Article id: 2, title: "Title 2", user_id: 2>
<#Article id: 4, title: "Title 4", user_id: 3>
...
<#Article id: N, title: "Title N", user_id: M>
In other words, I am looking to retrieve all articles but making those ordered with this “priority”: articles created by the given author returned first and then all other articles (that is, I would like to “push ahead” articles created by a given author).
How can I make that?
Note: I am looking for a Ruby on Rails implementation, maybe through the order method.
Your example is not that clear since you are searching for user_id 1 and a normal ordering by user_id would put those first anyway. I believe you mean to do something like:
In your example above,
@search_idshould be 1.