Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question