Reputation: 765
I have a Question table. It has a dummy question in it , i want to get the question in random but that dummmy question should always be on top in the returned ActiveRecord collection. I can get the records in random buy using Random()
function which is working fine but that dummy question has also random position which i dont want, i want it to be on first position. Any solution would be helpful.
Question table columns: id, statement, answer
The dummy question has blank statement.
Query i am using
Question.all.order("Random()")
I am using PostgreSQL.
Upvotes: 0
Views: 292
Reputation: 2877
First option:
select_clause = "(CASE WHEN (statement = '') THEN 0 ELSE Random() END) as dummy, questions.*"
Question
.select(select_clause)
.order('dummy')
Second option:
select_clause = "(statement <> '') as dummy, questions.*"
Question
.select(select_clause)
.order('dummy, Random()')
Edit: statement
shouldn't contain NULL in both options
Upvotes: 2