Search code examples
sqlruby-on-railsruby-on-rails-4active-record-query

Active record query for finding products in each city


I have two models as given below. Address table has an attribute city. Is it possible to find out total no. of products in each city using active record queries or do can it be done only through native sql query?

    class Product < ActiveRecord::Base
      has_one :address
    end

    class Address < ActiveRecord::Base
      has_many :products
    end

Solution

  • use this code:

     @no_of_products= Product.joins(:address).group("adrresses.city").count