0

Given the following select:

SELECT 
  COUNT(*) AS total,
  SUM(CASE approved WHEN 't' THEN 1 ELSE 0 END) AS num_approved,
  SUM(CASE soft_delete WHEN 't' THEN 1 ELSE 0 END) AS num_deleted
FROM model_name;

How might I translate this into something in my class ModelName definition, so that I can retrieve the values of total, num_approved, and num_deleted in my Rails application? I'm happy with any output (array, hash, accessors on a ModelName object) that puts the numbers at the Ruby level.

1 Answer 1

1
result = ModelName.select("
  COUNT(*) AS total, 
  SUM(CASE approved WHEN 't' THEN 1 ELSE 0 END) AS num_approved,
  SUM(CASE soft_delete WHEN 't' THEN 1 ELSE 0 END) AS num_deleted
").first

irb(main):278:0> result.total
=> 3041
irb(main):279:0> result.num_approved
=> 199464763
irb(main):280:0> result.num_deleted
=> #<BigDecimal:7fa0b7d79fd8,'0.19365329E8',9(18)>
Sign up to request clarification or add additional context in comments.

1 Comment

Will try this when I get in to work tomorrow. Thanks for the suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.