Today I Learned

hashrocket A Hashrocket project

Touch ActiveRecord::Associations

ActiveRecord::Associations#belongs_to has an option of touch.

If passed true, the associated object will have its updated_at/updated_on attributes set to current time.

You can also pass a symbol, in that case that attribute will be updated with the current time in addition to the updated_at/updated_on

class Comment < ApplicationRecord
  # When a comment is saved/destroyed, its post will
  # update the updated_at/updated_on to the current time
  belongs_to :post, touch: true

  # OR

  # When a comment is saved/destroyed, its post will update both
  # the updated_at/updated_on as well as comment_last_updated_at
  belongs_to :post, touch: :comment_last_updated_at
end

Note: No validations are performed when touching.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.