I stored string variables in a database, either ‘Abstain’, ‘Block’, ‘No’, or ‘Yes’. Currently I am grabbing these using an ORDER BY position however, instead of alphabetic order, I would like to order them like: ‘Block’, ‘No’, ‘Abstain’, ‘Yes’. Is there an easy way to do this in Rails?
My exact code for this is:
def self.unique_votes(motion)
Vote.find_by_sql("SELECT * FROM votes a WHERE created_at = (SELECT MAX(created_at) as created_at FROM votes b WHERE a.user_id = b.user_id AND motion_id = #{motion.id}) ORDER BY a.position")
end
NB: I am using Postgres SQL and am looking for a solution that i can use in the select statement Thanks!
This is one of the ways to do that. By the way, the best way to do such a thing is to have another table named
"Position"that identifies every value by a number and a foreign key in the"votes"table to reference the primary key of"Position"table. Also you can have another column named"Order"in the"Position"table to store those numbers and sort with. You should do these things in the insert time, not on every select.Cheers
Any way if it does not work as it should! you can try this one: