1

Working in rails, I am working to output a list of a User's classes for the Fall 2012 quarter. I have 3 models of importance here: User, Quarters, and Courses. Based on the other work I've done, I'm pretty certain my model associations are spot on, but for those interested:

  • User has_many :quarters and has_many :courses through quarters
  • Quarter belongs_to a user and HABTM courses (via the appropriate join table)
  • Course has_many users through quarters and HABTM quarters

I would like to implement a single query to gather the courses for a specific quarter such as

    current_user.quarters.where(:term => "Fall 2012").courses.each do |c|
       puts c.title
    end

But this results in an error "undefined method 'courses'" which I understand, but I would still like to access all the associated objects of an array of objects as the above code does instead of running the embedded loop that does what I need:

    current_user.quarters.where(:term => "Fall 2012").courses.each do |q|
        q.courses.each do |c|
            puts c.title
        end
    end

Thanks! Any ideas are appreciated :)

mattwd7
  • 57
  • 1
  • 8

1 Answers1

3

Like this :

current_user.courses.where("quarters.term" => 'Fall 2012')

Should work :)

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
  • Heroic response time and just the answer I was looking for. Is there somewhere I can go to learn more about this sort of thing? – mattwd7 Jul 28 '12 at 19:16
  • http://guides.rubyonrails.org/active_record_querying.html is a good start, specifically the part talking about joins. You have to understand that when declaring a has_many :through, rails does a join to get what you want. Therefore, you can apply conditions as if you were doing an explicit join! – Anthony Alberto Jul 28 '12 at 19:19
  • Also consider approving the answer if that fits your need :) – Anthony Alberto Jul 28 '12 at 19:24
  • Excellent resource. You have my sincerest gratitude – mattwd7 Jul 28 '12 at 20:05