Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group an Active Record relation on a has_many :through association

What I want to do is group records in an Active Record relation by a column on the :through model of a has_many :through relation, but I don't know what the best way is to go about it.

First, my models:

User has_many :subscriptions
     has_many :courses, :through => :subscriptions

Subscription belongs_to "both"

Course has_many :subs...
       has_many :users, :through => :subscriptions

I grab the courses related to the current_user like so: @courses = current_user.courses And I want to be able to do something like: @courses = current_user.courses.group('subscriptions.state') <-- That doesn't work obviously.

Also, after the records are grouped, what's the proper way to loop through that in the view to display them? In another place in my app, I've used group_by and each_pair respectively to accomplish this, but that was with one individual model.

like image 503
GorrillaMcD Avatar asked Aug 03 '12 23:08

GorrillaMcD


1 Answers

current_user.courses.select('courses.*, subscriptions.state').group_by(&:state)

This will return a hash and each key is a state. This works since the courses method is already doing a join.

like image 191
radixhound Avatar answered Oct 18 '22 07:10

radixhound