📜 ⬆️ ⬇️

New to Rails: Dirty Objects

Now you can check whether the object was modified (ActiveRecord) and what exactly was modified.

article = Article.find (: first)
article.changed? # => false



')
Track changes to individual attributes:

# attr_name_changed? accessor
article.title
# => Header
article.title = “New heading”
article.title_changed?
# => true


Get old attribute value:

# attr_name_was accessor
article.title_was
# => Header


Get old and new values:

# attr_name_change accessor
article.title_change
# => ["Title", "New Title"]


Get an array of changed attributes:

article.changed # => ['title']

Get a hash of changes:

article.changes
# => {'title' => [“Title”, “New Title”]}


This is how the object behaves:

article.changed?
# => true
article.save
# => true
article.changed?
# => false


However, if you modify the attribute value outside attribute = (), you will have to warn the model about it:

article = Article.find (: first)
article.title_will_change!
article.title.upcase!
article.title_change # => ['Title', 'TITLE']

Source: https://habr.com/ru/post/22825/


All Articles