Question

Can I create a postgresql view from the below code? Is it necessary?, because now it takes few second to load, but in the future I will have to add a date range on it. If yes, can someone help me to write it please.

    report = self.project_reports   
    results_total = report.where('value < ?', 50).group("key_id").select('key_id')
    fifty = report.where('value BETWEEN ? AND ?', 41, 50).group("key_id").select('key_id')
    forty = report.where('value BETWEEN ? AND ?', 31, 40).group("key_id").select('key_id')
    thirty = report.where('value BETWEEN ? AND ?', 21, 30).group("key_id").select('key_id')
    twenty = report.where('value BETWEEN ? AND ?', 11, 20).group("key_id").select('key_id')
    ten = report.where('value BETWEEN ? AND ?', 4, 10).group("key_id").select('key_id')
    three = report.where('value = ?', 3).group("key_id").select('key_id')
    two = report.where('value = ?', 2).group("key_id").select('key_id')
    one = report.where('value = ?', 1).group("key_id").select('key_id')
    pos = {fif: fifty.count.size, four: forty.count.size, thir: thirty.count.size, twen: twenty.count.size, te: ten.count.size, thr: three.count.size, tw: two.count.size, on: one.count.size, result_t: total}
Was it helpful?

Solution

This won't be a real 'view' in the SQL sense (you can only create that via a DDL query), but you can certainly build an ActiveRelation (which is probably what you meant anyhow). Note that you are switching between 'value' and 'position' arbitrarily, is that on purpose? I'm using 'value' for consistency sake here:

group_sql = <<-SQL
  CASE WHEN value = 1 THEN 'one'
       WHEN value = 2 THEN 'two'
       WHEN value = 3 THEN 'three'
       WHEN value <= 10 THEN 'ten'
       WHEN value <= 20 THEN 'twenty'
       WHEN value <= 30 THEN 'thirty'
       WHEN value <= 40 THEN 'forty'
       WHEN value <= 50 THEN 'fifty'
SQL
report = self.project_reports.where('value < 50').group(group_sql)
positions = report.count
positions['total'] = positions.values.sum
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top