Home > Software engineering >  retriving active record based on a has_many and belong_to on rails
retriving active record based on a has_many and belong_to on rails

Time:02-01

In my database schema i have a model named by City, and a model named by instituitions. so, City has_many instituitions, ans instituitions belongs_to City.

how do i retrive in cities_controller @cities = ??? the cities who has at least one institution.

CodePudding user response:

To find the cities that have at least one institution associated with them you can do:

City.joins(:institutions).distinct
  • In case you need to find the cities that don't have any institutions associated with them:
City.where.missing(:institutions)
  • Related