group method for activerecord. Docs are confusing? -
i don't means in rails tutorial:
group(*args) public allows specify group attribute:
user.group(:name)
=> select "users".* "users" group name returns array distinct records based on group attribute:
user.group(:name) [user id: 3, name: "foo", ...>, #user id: 2, name: "oscar", ...>]
i don't see grouping example gave...
group useful (i think) if trying count stuff in database or if join multiple tables. let me give few examples.
1. if want know how many users there in data base each name can do:
user.group(:name).count
this return hash looking this:
{ ann: 4, bert: 15, cecilia: 3 ... }
i not know why there many berts in database anyway...
2. if users have related records (for instance cars) can use first car included in activerecord model (the reason first because of how group works , further explained in link below)
user.joins(:cars).select('users.*, cars.model car_model, cars.name car_name').group('users.id')
now records in result have method called car_model
, 1 called car_name
.
you can count how many cars each user has 1 single query.
user.joins(:cars).select('users.*, count(cars.id) car_count').group('users.id')
now records have car_count
.
for further reading: mysql group tutorial
hope shed enough light on groups try them out little bit. not think can understand them until worked them little bit.
Comments
Post a Comment