D
D
deadsy2014-03-25 18:50:50
Ruby on Rails
deadsy, 2014-03-25 18:50:50

Ruby on Rails - how to set models to true?

I'm learning Ruby On Rails and I have a question about models.
The model has a boolean field. Only one entry in the collection can be set to true, the rest are reset to false.
How to correctly implement?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dron Krzh, 2014-03-25
@ walkman7

The easiest way is to select a model in which the field is true and replace it with false before saving. Or add a method that will be a trigger to replace the bool field.
api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
apidock.com/rails/v4.0.2/ActiveRecord/Persistence/...

I
Ivan Kryak, 2014-03-26
@sck_v

before_save :method

def method
  if column_changed? and column?
    Model.where(column: true).update_all(column: false)
  end
end

column - your column
Model - model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question