Pallavi Hegde
Pallavi Hegde

Reputation: 219

How to get the date when the particular attribute was first changed in rails

I have a boolean atrribute whose default is false. How can i get the date when the attribute was changed to true? The is_changed gives you if the value was changed. I want the date when the attribute was first changed. How do i get it in rails?

Upvotes: 1

Views: 755

Answers (4)

Thorin
Thorin

Reputation: 2034

I think there are two ways like above answer suggested to make a separate field and add date there when field changed first time or

you can use Public Activity gem that will log all the model activity with params. It creates a activities table based on this table you can get the date of the fields when it was first changed but it is a lengthy process

Upvotes: 0

Shiva
Shiva

Reputation: 12514

Well, looks like you basically want the feature of git in ActiveRecord records.

There are two ways

  • Use a separate col like changed_date. Update it whenever the field is changed for the first time.
    • I recommend this if your requirement is that simple. Do not use heavier gems.
  • Use libraries like VestalVersion or PaperTrail
    • these are helpful to track every activity in your records.
    • you can keep track of every changes, what its changed to and when
    • also you can revert your record to any point of time it was changed

Upvotes: 0

Salman Tahir
Salman Tahir

Reputation: 81

add attribute 'first_change' in that table which will save time stamp of every first change of the boolean attribute changed to true or false, then in model write the callback like this

before_update :check_changes

def check_changes
  if self.<boolean_attribute>.is_changed? and first_change.nil?
    self.update(first_change: Time.now)
  end
end

After this you can check when the boolean attribute was changed.

Upvotes: 1

Semyon Evgrafov
Semyon Evgrafov

Reputation: 106

You can wrap your boolean attribute in distinct model and from there you can easily trace when specific field was initially setted up or updated. In your current model you can't trace changing state of specific attributes, only the whole object, but it's not what you need I guess.

Upvotes: 0

Related Questions