Track dirty for not-persisted attribute in an ActiveRecord object in rails

前端 未结 4 1459
天命终不由人
天命终不由人 2021-02-05 03:27

I have an object that inherits from ActiveRecord, yet it has an attribute that is not persisted in the DB, like:

 class Foo < ActiveRecord::Base
   attr_acces         


        
4条回答
  •  春和景丽
    2021-02-05 04:05

    I figured out a solution that worked for me...

    Save this file as lib/active_record/nonpersisted_attribute_methods.rb: https://gist.github.com/4600209

    Then you can do something like this:

    require 'active_record/nonpersisted_attribute_methods'
    class Foo < ActiveRecord::Base
      include ActiveRecord::NonPersistedAttributeMethods
      define_nonpersisted_attribute_methods [:bar]
    end
    
    foo = Foo.new
    foo.bar = 3
    foo.bar_changed? # => true
    foo.bar_was # => nil
    foo.bar_change # => [nil, 3]
    foo.changes[:bar] # => [nil, 3]
    

    However, it looks like we get a warning when we do it this way:

    DEPRECATION WARNING: You're trying to create an attribute `bar'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc.
    

    So I don't know if this approach will break or be harder in Rails 4...

提交回复
热议问题