Non persistent ActiveRecord model attributes

后端 未结 5 1253
暗喜
暗喜 2020-12-10 00:20

I want to add to an existing model some attributes that need not be persisted, or even mapped to a database column. Is there a solution to specify such thing ?

5条回答
  •  抹茶落季
    2020-12-10 01:17

    From Rails 5.0 onwards you could use attribute:

    class StoreListing < ActiveRecord::Base
      attribute :non_persisted
      attribute :non_persisted_complex, :integer, default: -1
    end
    

    With attribute the attribute will be created just like the ones being persisted, i.e. you can define the type and other options, use it with the create method, etc.

    If your DB table contains a matching column it will be persisted because attribute is also used to affect conversion to/from SQL for existing columns.

    see: https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute

提交回复
热议问题