Is there any way to count users based on their province or state (Canada or US) with devise
and geocoder
? Tried to google but haven't found a solution.
user.rb
:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
# attr_accessible :address, :latitude, :longitude
geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
# Mandatory fields
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :business_name
end
Example of what I want to get: - Ontario: 89 - California: 32 - Quebec: 382 - etc...
I don't think there is a native way to do that. Implement methods to do what you want:
class User < ApplicationRecord
# your stuff...
def city
lat_lon = "#{latitude},#{longitude}"
Geocoder.search(lat_lon).first
end
def self.grouped_by_city
group_by{ |user| user.city }.map{|k,v| [k, v.count]}.to_h
end
end
Then you can call:
User.all.grouped_by_city
User.where(some_finder: some_value).grouped_by_city