mattwd7
mattwd7

Reputation: 57

RoR: Find all associated objects of an array of objects

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:

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

Upvotes: 1

Views: 1107

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

Like this :

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

Should work :)

Upvotes: 3

Related Questions