Question

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 :)

Was it helpful?

Solution

Like this :

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

Should work :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top