Saturday 15 August 2015

activerecord - Changing the format of returned records when using multiple groups in rails -



activerecord - Changing the format of returned records when using multiple groups in rails -

given table/model called assignment fields:

id student_id grade (e.g. a, b, c) ... other stuff

how can list of students , how many of each grade have?

the nearest i've got has been:

assignment.group(:student_id).group(:grade).count

but gives me info in format:

{[student_id, grade] => count, [student_id, grade] => count, ...}

eg.

{ [1, "a"] => 8, [1, "b"] => 6, [2, "a"] => 7, [2, "f"] => 5 }

is there way can array on value side can loop on , print out students results? i.e. this:

{ 1 => {"a" => 8, "b" => 6}, 2 => {"a" => 7, "f" => 5} }

the nearest you've got final one. now, need reindex results:

student_grades_count = { [1, "a"] => 8, [1, "b"] => 6, [2, "a"] => 7, [2, "f"] => 5 } student_grades_count = student_grades_count.reduce({}) |sum, ((student_id, grade), count)| sum[student_id] ||= {} sum[student_id][grade] = count sum end

ruby-on-rails activerecord

No comments:

Post a Comment