# Many-to-many relationship with multiple models?

**URL:** <https://www.ruby-forum.com/t/many-to-many-relationship-with-multiple-models/56275>\
**Category:** Rails\
**Created:** [March 29, 2006, 11:44pm UTC](https://www.ruby-forum.com/t/many-to-many-relationship-with-multiple-models/56275 "2006-03-29T23:44:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![adambeazley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@adambeazley](https://www.ruby-forum.com/u/adambeazley)\
**Post date:** [March 29, 2006, 11:44pm UTC](https://www.ruby-forum.com/t/many-to-many-relationship-with-multiple-models/56275/1 "2006-03-29T23:44:16Z")

</div>

I have a simple CMS I’m creating, and the primary model is the  
“listing”. A listing habtm (has\_and\_belongs\_to\_many) categories (up to  
two) - allowing the listing to print its categories and a category to  
print its listings. I also need subcategories, which are different from  
categories in two ways: a listing can have as many subcategories (from  
it’s two categories) as it wishes, and subcategories are displayed  
differently in both administration and display views.

So what I have is:

Class Listing \< ActiveRecord::Base

has\_and\_belongs\_to\_many :categories  
has\_and\_belongs\_to\_many :subcategories

…

end

Class Subcategory \< ActiveRecord::Base

has\_and\_belongs\_to\_many :listings  
belongs\_to :categories

end

Class Category \< ActiveRecord::Base

has\_and\_belongs\_to\_many :listings  
has\_many :subcategories

…

end

Is this allowed? I ask because I can’t create a listing with  
subcategories (from the admin UI) - the UI works fine, there are no  
errors, but the new listing has no subcategories and the MySQL DB isn’t  
updated.

-Adam
