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.
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.
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