# Help with associations

**URL:** <https://www.ruby-forum.com/t/help-with-associations/114302>\
**Category:** Rails\
**Created:** [September 11, 2007, 2:13am UTC](https://www.ruby-forum.com/t/help-with-associations/114302 "2007-09-11T02:13:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![itchy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@itchy](https://www.ruby-forum.com/u/itchy)\
**Post date:** [September 11, 2007, 2:13am UTC](https://www.ruby-forum.com/t/help-with-associations/114302/1 "2007-09-11T02:13:38Z")

</div>

Hi I have a site that has the following model declarations:

User:

has\_and\_belongs\_to\_many :categories  
has\_and\_belongs\_to\_many :sub\_categories

Item:

has\_and\_belongs\_to\_many :sub\_categories  
has\_and\_belongs\_to\_many :categories

Category:  
has\_many :sub\_categories  
has\_and\_belongs\_to\_many :items  
has\_and\_belongs\_to\_many :users

SubCategory:  
belongs\_to :category  
has\_and\_belongs\_to\_many :items  
has\_and\_belongs\_to\_many :users

So when a user registers they select a number of categories and if they  
want they can also select sub categories for more fine grained  
interests. When a new item is added to the site, part of the item  
registration process is to select the categories and sub-categories to  
which the item belongs.

The bit that i would like advice/help/suggestions on is one a day i want  
to run a cron job to go through the items added that day and to find all  
the user-registered categories and sub-categories and find where they  
intersect with the items categories and sub-cats and then produce a user  
specific email telling that user about items they may be interested in.

Basically is it possible to iterate through the list of items and write  
something like

item.categories.users and get a list of the users who registered  
interest in this items categories?

Am i asking too much here? Will i just have to write some big iterative  
function or is there an easier smarter approach?

Any help gratefully received.

best regards  
caspar

---

<div class="post-metadata">

**Author:** ![itchy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@itchy](https://www.ruby-forum.com/u/itchy)\
**Post date:** [September 11, 2007, 8:09am UTC](https://www.ruby-forum.com/t/help-with-associations/114302/2 "2007-09-11T08:09:34Z")

</div>

IIRC, you can iterate only one level in depth, so you might have a  
structure like:

items.categories.each do |category|  
category.users.each do |user|  
# do something here  
end  
end
