Lucas Fernando
Lucas Fernando

Reputation: 66

retriving active record based on a has_many and belong_to on rails

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.

Upvotes: 0

Views: 42

Answers (1)

Gogamar
Gogamar

Reputation: 173

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)

Upvotes: 2

Related Questions