All threads / How do i save the initial time a boolean went from false to true

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do i save the initial time a boolean went from false to true

Dim Dir asked in Rails

I have a boolean column in my table and a datetime related to it. I want to be able to track down when the boolean initially turns true. In the model I have tried

def example
if boolean_field == true
datetime_field = time.now
end
end
but the problem with that is when the boolean is set to true, the datetime_field will keep updating everytime i reload the page or database since the boolean will always be in a constant state of true. I have also try to use rails dirty on it with:

boolean_field_changed?
but that method doesn't seems to update the datetime column at all. P.S i do have a before_save callback on the method.

any help on how i can save the initial time once the boolean_field changes from false to true will be much appreciated. thanks in advance

Hey Dim,

Just check to see if the time field is blank

def example
  if boolean_field == true && datetime_field.blank?
      datetime_field = Time.now
  end
end

Hey Jacob, Thank you so much, can't believe this was going over my head. hahah much appreciated man

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.