Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inspecting old state of ActiveRecord object "before changes" #48243

Closed
TiesWestendorp opened this issue May 17, 2023 · 1 comment
Closed

Inspecting old state of ActiveRecord object "before changes" #48243

TiesWestendorp opened this issue May 17, 2023 · 1 comment

Comments

@TiesWestendorp
Copy link

TiesWestendorp commented May 17, 2023

Sometimes it's nice to be able to access a version of an ActiveRecord object before certain changes are applied, e.g.:

class Foo < ActiveRecord::Base
   def foobar
      some_attribute
   end

   around_update :bar
   def bar
      pp self.foobar # At this point, I'd like to be able to inspect the 'old' state
      yield
      pp self.foobar
   end
end

Currently, ActiveRecord::Dirty provides some methods to inspect changes and older values of specific attributes through changes and *_was, but not the entire previous state. Having access to it would allow you to call instance methods using the old state.

I propose to add the following instance method to ActiveRecord::Dirty:

def self_was
  self.changes.each_with_object(self.dup) {|(attribute,(previous_value,_)), object|
    object.write_attribute(attribute, previous_value)
  }
end

So we can replace self by self_was before the yield and get the behavior that we want.

If this is not the right repo to suggest this in, please let me know. Apologies for ignoring the issue template, but it was not really applicable for a feature request, so ignoring it seemed more appropriate then shoehorning this suggestion into it.

@eileencodes
Copy link
Member

Hi @TiesWestendorp thanks for the issue. We don't accept feature requests on the issues tracker, we reserve it for bugs in the framework. I'm not sure how possible this would be to implement or whether it's really useful to a wide range of applications. It would probably be best for you to post on the forum and see what others think. If you want to try out an implementation please open a PR. If you need help contributing, you can use the contributors discord. Thanks for understanding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants