# Should be a fairly simple activerecord question

**URL:** <https://www.ruby-forum.com/t/should-be-a-fairly-simple-activerecord-question/92581>\
**Category:** Rails\
**Created:** [April 21, 2007, 12:43am UTC](https://www.ruby-forum.com/t/should-be-a-fairly-simple-activerecord-question/92581 "2007-04-21T00:43:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mendake](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/d6d6ee/32.png) [@mendake](https://www.ruby-forum.com/u/mendake)\
**Post date:** [April 21, 2007, 12:43am UTC](https://www.ruby-forum.com/t/should-be-a-fairly-simple-activerecord-question/92581/1 "2007-04-21T00:43:01Z")

</div>

This should be very clear to me, but for some reason it’s not, and I  
can’t seem to find any examples that help me. My models looks like this:

class Product \< ActiveRecord::Base  
has\_many :company\_products  
end

class CompanyProduct \< ActiveRecord::Base  
belongs\_to :product  
end

How do I find all Product records that have a CompanyProduct.company\_id  
of, say 36?

I suppose I could do a find\_all statement with an include, but it seems  
there should be a much easier, ready-made ActiveRecord solution rather  
than creating my very own joins. How would that work?

---

<div class="post-metadata">

**Author:** ![mendake](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/d6d6ee/32.png) [@mendake](https://www.ruby-forum.com/u/mendake)\
**Post date:** [April 21, 2007, 1:44am UTC](https://www.ruby-forum.com/t/should-be-a-fairly-simple-activerecord-question/92581/2 "2007-04-21T01:44:53Z")

</div>

Ahhh, yes, that sounds like what I need. Thank you.

---

<div class="post-metadata">

**Author:** ![mendake](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/d6d6ee/32.png) [@mendake](https://www.ruby-forum.com/u/mendake)\
**Post date:** [April 21, 2007, 1:17am UTC](https://www.ruby-forum.com/t/should-be-a-fairly-simple-activerecord-question/92581/3 "2007-04-21T01:17:17Z")

</div>

On Apr 20, 2007, at 6:43 PM, MenDAKE wrote:

> end
> 
> How do I find all Product records that have a  
> CompanyProduct.company\_id  
> of, say 36?
> 
> I suppose I could do a find\_all statement with an include, but it  
> seems  
> there should be a much easier, ready-made ActiveRecord solution rather  
> than creating my very own joins. How would that work?

Assuming that “CompanyProduct.company\_id” means that you just forgot  
to mention:

> class CompanyProduct \< ActiveRecord::Base  
> belongs\_to :product  
> belongs\_to :company  
> end

And you can add:

class Company \< ActiveRecord::Base  
has\_many :company\_products  
has\_many :products, :through =\> :company\_products  
end

Then it’s just:

Company.find(36).products

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
