Search code examples
ruby-on-railsrails-activerecord

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.


Solution

  • 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)