ActiveRecord model attribute definition with type caster and default

64 views
Skip to first unread message

Benji

unread,
Dec 23, 2014, 4:19:14 AM12/23/14
to rubyonra...@googlegroups.com
[Braindump]
I stumbled on the code to define an attribute in the model. Since my personal opinion is that default and type logic of an attribute is the responsibility of the model and not of a database column type I was really happy to see the code appear in rails:


The current implementation of the attribute method requires a mandatory second argument type caster object. Since active record has a very good mechanism of creating a good default type caster based on a database column I suggest to use it for this method. In pseudo monkey patch code:

class MyModel < ActiveRecord::Base
  def self.attribute(name, options = {})
    type_caster = options.delete(:type) || columns_hash[name.to_s].cast_type
    super(name, type_caster, options)
  end


  attribute :my_number, default: 5 
  attribute :price_in_cents, type: MoneyType.new
end

aka, make the type caster an option, not a required argument and fall back to the default based on the database column type. 

Thanks for all the good work!! 

Benjamin ter Kuile


Sean Griffin

unread,
Dec 23, 2014, 9:57:54 AM12/23/14
to rubyonra...@googlegroups.com
This is not currently public API, the final API will likely support default values when it is made public in the future.

Benji

unread,
Dec 23, 2014, 12:56:17 PM12/23/14
to rubyonra...@googlegroups.com
Nice!

Benji

unread,
Nov 16, 2015, 7:26:26 AM11/16/15
to Ruby on Rails: Core
Any news on this topic? The current master branch code still does not support inferring the type as a default when it is obvious from the database column, aka:

class StoreListing < ActiveRecord::Base
  attribute :my_string, :string, default: "new default"
end

Should be:

class StoreListing < ActiveRecord::Base
  attribute :my_string, default: "new default"
end

since the database column type is a string type.


On Tuesday, 23 December 2014 15:57:54 UTC+1, Sean Griffin wrote:

Sean Griffin

unread,
Nov 16, 2015, 8:26:54 AM11/16/15
to Ruby on Rails: Core
I disagree, just set a database default if that's your use case
Reply all
Reply to author
Forward
0 new messages