A
A
Anton Ipatov2019-08-15 18:38:22
Ruby on Rails
Anton Ipatov, 2019-08-15 18:38:22

How to make it so that when creating a Place model, the continent of the country is automatically added?

I use Ruby on Rails 5.2 and Mongoid 7.0
. I have a Place model where, using Geocoder, the name of the country is determined by coordinates, how to make it so that after that you can add a continent to the country (Asia, Africa, North America, South America, Antarctica, Europe , Australia) where is it located?

class Place
  include Mongoid::Document
  include Mongoid::Timestamps
  include Geocoder::Model::Mongoid
  field :coordinates, type: Array
  field :latitude, type: Float
  field :longitude, type: Float
  field :created_at, type: Time

  field :country, type: String
  field :continent, type: String
 
  before_validation :initialize_coordinates

  def initialize_coordinates
    self.coordinates = [self.longitude.to_f, self.latitude.to_f]
  end

  def set_coordinates
    [self.longitude, self.latitude].compact.join(', ')
  end

  reverse_geocoded_by :coordinates do |obj,results|
    if geo = results.first
      obj.address = geo.address
      obj.city = geo.city || geo.state
      obj.state = geo.state
      obj.state_code = geo.state_code
      obj.postal_code = geo.postal_code
      obj.country = geo.country
      obj.country_code = geo.country_code
    end
  end
  after_validation :reverse_geocode
  after_save :update_position_for_other, if: :current_position_changed?
end

I understand that the model should be something like
class Place
  ......

  after_save :update_continent

    def update_continent
    cont = self.country
    case cont
    when 'United States', 'Grenada'
      'North America'
    when 'Netherlands', 'Spain'
      'Europe'
    end

    self.continent = cont
  end
 end

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question