Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Users with an attribute for each Group?

My models: User, Group, and Membership. Users can have many groups through memberships, and vice-versa. I want to create a tool for website admins that produces a large table with the following specification:

Every row represents a user, Every column represents a group, In each cell of the table there is a boolean indicating whether the user belongs to the group.

What would be the best way to do this? Is it possible to write a single SQL query that achieves it (i.e. User.find_by_sql)? If not, how else?

p.s. I actually need a bit more than this (I need two columns per group, the first one indicating membership, and the second one counting how many meetings the user has attended in that group, but this involves the Meeting model, so I'll leave that for later.

like image 248
gdiazc Avatar asked Dec 12 '25 20:12

gdiazc


1 Answers

Assuming that you're asking about the backend methodology not the data visualization aspect most of what JuanM. said is correct. One thing I would recommend is avoid writing his 'get_groups' method and just set up a 'has many through' relationship between users in groups. To do so put

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, through: :memberships
end

In your Users model and vice versa in your Groups model (assuming memberships 'belongs_to' both). Then you'll have a '.groups' method on any User instance and a '.users' method on any Group instance

like image 55
SomeSchmo Avatar answered Dec 15 '25 10:12

SomeSchmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!