A
A
Anton Ipatov2019-07-26 00:56:05
Ruby on Rails
Anton Ipatov, 2019-07-26 00:56:05

How to make a dependency inside a Rails model?

I use Ruby on Rails and Mongoid.
There is a Place model where users can mark their location and set current_position to true .
It is necessary that when the user creates a new location, when he sets current_positon true from his other locations, this value becomes false .

class Place
  include Mongoid::Document

  field :current_position, type: Boolean, default: "false"

  validates :user_id, presence: true

  belongs_to :user, touch: true
 
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N. Bekseitov, 2019-07-26
@IpatovAnton

class Place
  include Mongoid::Document

  field :current_position, type: Boolean, default: "false"

  validates :user_id, presence: true

  belongs_to :user, touch: true

  after_save :update_position_for_other, if: :current_position_changed?

  private

  def update_position_for_other
    Place.where(:id.ne => id, user_id: user_id).update_all(current_position: false) if current_position
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question