Answer the question
In order to leave comments, you need to log in
How to create an association in Rails?
Hello, I'm using Ruby on Rails 5.2, Mongoid 7.0 and Geocoder
. I have a Place model where the user's location is created, I need it to be associated with another City model via field : city when creating a location (so that it is created new or added to an existing one, I understand that something like this should look like self.city = City.find_or_create_by(name: name) if name.present? ).
place.rb
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 :city, type: String
field :current_position, type: Boolean, default: "true"
belongs_to :user, touch: true
belongs_to :city, touch: true
before_validation :initialize_coordinates
after_validation :reverse_geocode
def initialize_coordinates
self.coordinates = [self.longitude.to_f, self.latitude.to_f]
end
reverse_geocoded_by :coordinates do |obj,results|
if geo = results.first
obj.city = geo.city || geo.state
end
end
end
class City
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :created_at, type: Time
has_many :places
end
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question