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

前端 未结 4 1455
天命终不由人
天命终不由人 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 03:52

    ActiveRecord has the #attribute method (source) which once invoked from your class will let ActiveModel::Dirty to create methods such as bar_was, bar_changed?, and many others.

    Thus you would have to call attribute :bar within any class that extends from ActiveRecord (or ApplicationRecord for most recent versions of Rails) in order to create those helper methods upon bar.

    Edit: Note that this approach should not be mixed with attr_accessor :bar

    Edit 2: Another note is that unpersisted attributes defined with attribute (eg attribute :bar, :string) will be blown away on save. If you need attrs to hang around after save (as I did), you actually can (carefully) mix with attr_reader, like so:

    attr_reader :bar
    attribute :bar, :string
    
    def bar=(val)
      super
      @bar = val
    end
    

提交回复
热议问题