Fernando Maymone
Fernando Maymone

Reputation: 755

How to make a query on a has_many_and_belongs_to association?

I have an instance called Year and another called HighlightCategory. Just like this:

class HighlightCategory < ActiveRecord::Base
   has_and_belongs_to_many :years 
end

class Year < ActiveRecord::Base
  :name
  has_and_belongs_to_many :highlightCategories
end

Im doing a controller that wants to check all the HighlightCategories from a specific year. Like this:

if (params[:year])
    @year = Year.where(year: params[:year] )
    @subjects = HighlightCategory.where(HOW TO MAKE IT)
else

I want to make a query where I just return the HighlightCategories that have association with this specific year.

How can I make it?

Upvotes: 0

Views: 58

Answers (3)

Sovalina
Sovalina

Reputation: 5609

According to your previous question, you pass a year instance as a params of your link_to.
In your controller it returns an id not an object of year.

So you can retrieve the corresponding year like this:

@year = Year.find(params[:year])

Then you have a has_and_belongs_to_many relationship between Year and HighlightCategory. To find the highlights_categories for this specific year you can just do:

@subjects = @year.highlights_categories

However, be careful of your model and table naming convention: HighlightCategory model name must have a highlight_categories table name, with underscore (source).
And the relationship for Yearmust be:

has_and_belongs_to_many :highlight_categories 

Upvotes: 2

Kartikey Tanna
Kartikey Tanna

Reputation: 1459

Eager loaded:

@subjects = HighlightCategory.includes(:years).where(years: { year: @year })

Lazy loaded:

@subjects = HighlightCategory.joins(:years).where(years: { year: @year })

You can read about joins vs includes over here.

In short, while iterating over the collection in @subjects, if the joins is used then the data will be lazy loaded whereas includes will eager load all the records in the memory.

Both have their own use-cases.

Upvotes: 0

aaron.v
aaron.v

Reputation: 539

I would do

@subjects = HighlightCategory.joins(:years).where(years: {year: params[:year]})

using joins adds the table to your query, and this allows you to query from your years table

Upvotes: 0

Related Questions