grabury
grabury

Reputation: 5559

How to find records from 2 many to many relationships

I want to find the businesses of a certain category inside a certain estate

I have the following models

Business has many Categories through Categorizations
Category has many Businesses through Categorizations

Business has many Estates through Localizations
Estate has many Businesses through Localizations

In the category show action I have

def show
  @category = Category.find(params[:id])
  @estate = Estate.find(current_user.estate_id)
  @businesses = @estate.businesses
end

The obvious problem is that it is returning all businesses for an estate no matter which category it belongs to. I tried to add a .where("category_id = ?", @category_id) but I get column does not exist error

Upvotes: 1

Views: 38

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

As it seems to work, here's the suggestion again as an answer :)

@businesses = @estate.businesses.joins(:categories).where(categories: {id: @category.id})

Upvotes: 1

Related Questions