Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group function in belongs_to association rails

user.rb

enum gender: [:Male, :Female] 
belongs_to :qualification

qualification.rb

has_many :users

When I query

User.all.group(:gender).count.map { |k, v| [User.genders.key(k), v] }.to_h

It gives me

{"Male"=>18, "Female"=>1}

But I doesn't know to do same for qualification because association is involve in it.How I do it?

User.all.group(:qualification_id).count.map { ??? }
like image 873
Haseeb Ahmad Avatar asked Feb 07 '23 21:02

Haseeb Ahmad


1 Answers

You can perform a join between your associated models by using joins() with the name of the association, and then group by any column of the joined model.

For example, if you want to group by the name column of qualification :

User.joins(:qualification).group('qualifications.name').count

Use the symbol :qualification describing the relation in the joins method, but use the table name 'qualifications' in the group method in order to specify the column. This will generate a SQL request like this :

SELECT COUNT(users.id)
FROM users
INNER JOIN qualifications ON users.qualification_id = qualifications.id
GROUP BY qualifications.name
  • Documentation of ActiveRecord (search for joins) : http://guides.rubyonrails.org/active_record_querying.html
  • Explanation of SQL JOINS : http://www.w3schools.com/sql/sql_join.asp
like image 74
Caillou Avatar answered Feb 16 '23 03:02

Caillou