1

I want there always to be at least one document in database which has a field titled "selected" set to true. How do I do that? Most probably I have to use callbacks, but which one: before (or after) _create, _upsert, _update?

And how can I ensure that it will be set to true whatever operation executes: create, update, upsert...? I guess that would not be right to create a callback for each of them.

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

1 Answers1

2

after_save always runs after create & update

so you could do:

after_save do |your_class|
  your_class.update_column(:selected, true) unless YourClass.where(selected: true).exists?
end

NB./ update_column should not fire the after_save again!

Community
  • 1
  • 1
gef
  • 7,025
  • 4
  • 41
  • 48