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 { ??? }
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
joins
) : http://guides.rubyonrails.org/active_record_querying.html
JOINS
: http://www.w3schools.com/sql/sql_join.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With