jedi
jedi

Reputation: 2198

ActiveRecord Associations method for fetching associated objects

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?

Upvotes: 1

Views: 61

Answers (2)

rubhan
rubhan

Reputation: 34

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 %>

Upvotes: 0

Satishakumar Awati
Satishakumar Awati

Reputation: 3798

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.

Upvotes: 1

Related Questions