Question: I have three models Brand, Category and Country in many-to-many association meaning that each brand may belong to many categories, each category may have many brands, each country may have many categories and brands I need to know a way to fetch categories that the brands were put into.

So far I have this:

```
@brands = Brand.includes(:categories)

```

which creates the association between brand and category and I am stuck. I don't know how to fetch the categories that the brands were put into. Can you help me?

Answer: 
You have to make use of **has\_and\_belongs\_to\_many** association between models **Brand** and **Category**.

Rails guides does a great job in describing how it works.
<http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association>.
Create a HABTM relationship. Start from creating a new model `category` then create a new migration and named it `brands_categories` add references of both category and brand in your new migration. like `rails g migration brands_categories brand:references category:references`. Then permit `{:category_ids => []}, :categories_attributes => [:category]` in your brand\_params. To add category in your brand view form something like this   

`<% Category.all.each do |cat| %>`   

`<div class="checkbox">`  

`<label>`  

`<%= check_box_tag "product[category_ids][]", cat.id, @product.categories.include?(cat) %>`  
 `<%= cat.category %>`  

`</label>`  

`</div>`  

`<% end %>`