Reputation: 13
we have two models
user have many articles i need When an user views all articles, see their own articles first.
my idea
first query return articles related to query
Article.where(user_id: user_id)
second query
Article.where.not(user_id: user_id)
and merge result
second Idea get all articles and select method in ruby
but i need best way make this
Upvotes: 0
Views: 110
Reputation: 106932
You could run one query but sort the articles with SQL depending on if they have a matching user_id
:
Article.order(Arel.sql("CASE user_id WHEN #{user_id} THEN 0 ELSE 1 END"))
Note: order
does not support multiple arguments and input sanitization out of the box. Use this only, when you are sure that the user_id
contains only a valid user id, for example, be using current_user.id
instead of user_id
In Rails 7 there will be a new method called in_order_of
which would allow writing the same functionality like this:
Article.in_order_of(:user_id, user_id)
Upvotes: 5
Reputation: 1206
More programmatic approach
articles = Article.arel_table
case_statement = Arel::Nodes::Case.new(articles[:user_id])
.when(user_id)
.then(0)
.else(1)
Article.order(case_statement)
Upvotes: 1