Search

How To Do A Case Or Switch Statement In SQL And Rails

Posted by Weston Ganger on August 18, 2016

In one of my Rails apps I needed to do a case statement for a search. SQL has a built in function for this fortunately.


CASE current_state 
WHEN 'Created' THEN 1 
WHEN 'In Progress' THEN 2 
WHEN 'Completed' THEN 3 
END

Some Rails examples


# Use the %q method to make the sql string more readable
Post.order(%q{
  CASE current_state 
  WHEN 'Created' THEN 1 
  WHEN 'In Progress' THEN 2 
  WHEN 'Completed' THEN 3 
  END
})

# OR a more dynamic method

the_order = ['Created','In Progress','Completed']
the_sql = "CASE current_state"
the_order.each_with_index do |x,i|
  the_sql += " WHEN #{x} THEN #{i}"
end
the_sql += " END"

Post.order(the_sql)


Related External Links:


Posted in Rails and Tagged with sql rails 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts