# Joining on multiple tables

**URL:** <https://www.ruby-forum.com/t/joining-on-multiple-tables/113017>\
**Category:** Rails\
**Created:** [August 26, 2007, 7:22am UTC](https://www.ruby-forum.com/t/joining-on-multiple-tables/113017 "2007-08-26T07:22:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wheels](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7bcc69/32.png) [@wheels](https://www.ruby-forum.com/u/wheels)\
**Post date:** [August 26, 2007, 7:22am UTC](https://www.ruby-forum.com/t/joining-on-multiple-tables/113017/1 "2007-08-26T07:22:58Z")

</div>

I’m having trouble trying to join on multiple tables. In this example,  
I want to do fetch of companies in a specified category and location.  
The pagination code is using the will\_paginate plugin. Any pointers?  
Do I need to resort to a find\_by\_sql?

```
  @category = Category.find(params[:category_id])
 @location = Location.find(params[:location_id])
  #Need to join on location id too, how?
  @companies = @category.companies.paginate :all, :per_page =>

```

10, :page =\> params[:page]

Thanks,  
Tommy

---

<div class="post-metadata">

**Author:** ![wheels](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7bcc69/32.png) [@wheels](https://www.ruby-forum.com/u/wheels)\
**Post date:** [October 7, 2007, 2:27am UTC](https://www.ruby-forum.com/t/joining-on-multiple-tables/113017/2 "2007-10-07T02:27:02Z")

</div>

Hi Tommy,

There is a will\_paginate group:  
[http://groups.google.com/group/will\_paginate](http://groups.google.com/group/will_paginate)

Ask your question there, please.  
Thanks,

- Mislav

---

<div class="post-metadata">

**Author:** ![wheels](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7bcc69/32.png) [@wheels](https://www.ruby-forum.com/u/wheels)\
**Post date:** [October 7, 2007, 8:37pm UTC](https://www.ruby-forum.com/t/joining-on-multiple-tables/113017/3 "2007-10-07T20:37:28Z")

</div>

Can you use a dynamic, attribute-based finder method with your has\_many  
declaration? Or use an association extension if Rails doesn’t create it  
automatically. Like this:

@category.companies.find\_by\_location(@location)

This method won’t be terribly fast though since you are performing 3-4  
queries. I would consider a specialized query method like  
“Company.find\_by\_category\_and\_location(cat\_id, loc\_id)”.

mike

wheels wrote:

> ```
> @category = Category.find(params[:category_id])
> @location = Location.find(params[:location_id])
> #Need to join on location id too, how?
> @companies = @category.companies.paginate :all, :per_page =>
> 
> ```
> 
> 10, :page =\> params[:page]
