# ActiveRecord Join over multiple tables

**URL:** <https://www.ruby-forum.com/t/activerecord-join-over-multiple-tables/125715>\
**Category:** Rails\
**Created:** [January 11, 2008, 12:34pm UTC](https://www.ruby-forum.com/t/activerecord-join-over-multiple-tables/125715 "2008-01-11T12:34:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [January 11, 2008, 12:34pm UTC](https://www.ruby-forum.com/t/activerecord-join-over-multiple-tables/125715/1 "2008-01-11T12:34:09Z")

</div>

Hey I have a DB Model with the following tables

users, courses, users\_courses and coursecategories

users \<1:n\> users\_courses \<n:1\> courses \<n:1\>

I have the models set up and they sheem to work.

I can do something like this

user\_courses = User.find\_by\_id(1).courses (resolves the n:m relation and  
returns the right course objects)

What i need is something like this:

user\_categories = User.find\_by\_id(1).courses.coursecategorie (doesn’t  
work)

I want to query all the categories a user has courses in.

How do i do that?

thx

---

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [January 11, 2008, 12:57pm UTC](https://www.ruby-forum.com/t/activerecord-join-over-multiple-tables/125715/2 "2008-01-11T12:57:18Z")

</div>

Sheems to work with:

User.find\_by\_id(1).courses.collect { |c| c.coursecategorie }.flatten

ck

Christian K. wrote:

> Hey I have a DB Model with the following tables
> 
> users, courses, users\_courses and coursecategories
> 
> users \<1:n\> users\_courses \<n:1\> courses \<n:1\>
> 
> I have the models set up and they sheem to work.
> 
> I can do something like this
> 
> user\_courses = User.find\_by\_id(1).courses (resolves the n:m relation and  
> returns the right course objects)
> 
> What i need is something like this:
> 
> user\_categories = User.find\_by\_id(1).courses.coursecategorie (doesn’t  
> work)
> 
> I want to query all the categories a user has courses in.
> 
> How do i do that?
> 
> thx

---

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [January 11, 2008, 12:58pm UTC](https://www.ruby-forum.com/t/activerecord-join-over-multiple-tables/125715/3 "2008-01-11T12:58:36Z")

</div>

On 11 Jan 2008, at 11:34, Christian K. wrote:

> How do i do that?

Unfortunately you can’t nest has\_many :throughs  
at a more basic level,

CourseCategory.find :all, :joins =\> :user\_courses, :conditions =\>  
[‘user\_courses.user\_id = ?’, 1]

Should get them(possibly with duplicates though)

Fred
