DEV Community

mmyoji
mmyoji

Posted on • Updated on

touch triggers other touches

ActiveRecord::Persistence#touch is a useful method and I like it.

But I didn't really understand its spec well and it caused a deadlock in our Rails project. You have to care about its impact.

class Post < ApplicationRecord
  belongs_to :post_category, touch: true
  belongs_to :writer, touch: true
end

# This class is a pseudo class
class SomeClass
  def initialize(post, args)
    @post = post
    # ...
  end

  def call
    # ...
    @post&.touch(:published_at)
    # triggers following:
    # @post.post_category.touch
    # @post.writer.touch
  end
end
Enter fullscreen mode Exit fullscreen mode

In SomeClass#call, Post#touch is called and I thought this only update the post.published_at, but also update post_category.updated_at and writer.updated_at.

The above code is just an example and it might be a trouble when you use touch casually in the real application.

You just care about logs before deployment :)

Top comments (0)