Search code examples
ruby-on-railsactiverecordruby-on-rails-5ruby-on-rails-5.2

saved_change_to_* does't work correctly when using "activerecord-typedstore" gem with Rails 5.2


We are using activerecord-typedstore gem with Rails 5.2 application. Everything is fine except the "dirty attributes" methods in after callbacks. According to the gem's page, it should work with Rails 5.2 but there is a simple way to reproduce the issue

I haven't find a way to fix it myself so I posted an issue to the gem's github: https://github.com/byroot/activerecord-typedstore/issues/78

This example demonstrates the issue:

class Profile < ApplicationRecord
  typed_store :properties do |p|
    p.string :phone
  end

  after_save :debug
  def debug
    puts "saved_change_to_phone #{saved_change_to_phone.inspect}"
  end
end

p = Profile.create(phone: "123")
p.save
p = Profile.last
p.phone = "456"
p.save

# Displays:
# saved_change_to_phone nil

Is it possible to get the standard Rails 5.2 behavior for stored attributes in after callbacks? Or maybe there is an alternative gem that I can use instead?


Solution

  • I have tested your example:

    The only way I was able to make it work is to disable accessors like so:

    # frozen_string_literal: true
    
    class Profile < ApplicationRecord
      validates :phone, presence: true
      typed_store :properties, accessors: false do |p|
        p.string :phone
      end
    
      after_save :debug
      def debug
        puts "saved_change_to_phone #{saved_change_to_phone.inspect}"
      end
    end
    

    The results:

    first second

    I don't know if this is your desired behaviour though.