Home > Software design >  Ruby on Rails: How to select all Cities which have at least 1 company and company category == 14
Ruby on Rails: How to select all Cities which have at least 1 company and company category == 14

Time:06-15

How to select all Cities which have at least 1 company and company category == 14.

City.includes(:companies).where('companies.category_id' => @category.id)

Associations

City    
has_and_belongs_to_many :categories   
has_and_belongs_to_many :companies 

Company   
has_and_belongs_to_many :categories   
has_and_belongs_to_many :cities 

Category   

has_and_belongs_to_many :companies   
has_and_belongs_to_many :cities

CodePudding user response:

If you implemented all associations as convention suggests and you have these tables: cities_companies and categories_companies than you can do it with this query:

City.distinct.joins(companies: :categories).where(categories: { id: @category.id })
  • Related