Как создать ассоциацию в Rails?

Здравствуйте, я использую Ruby on Rails 5.2, Mongoid 7.0 и Geocoder

У меня есть модель Place где создается местоположения пользователя, мне нужно чтобы при создание местоположения оно ассоциировалось с другой моделью City через field :city (чтобы она создавалась новая либо добавлялась в уже существующую, понимаю что примерно это должно выглядить так 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


city.rb
class City
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String
  field :created_at, type: Time

  has_many :places
end
  • Вопрос задан
  • 141 просмотр
Пригласить эксперта
Ответы на вопрос 1
inf
@inf
DevOps Engineer
Не проще city_id передавать из формы?
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы