Validates inclusion of include fails at plugin.

26 views
Skip to first unread message

Rupesh Jayaprakash

unread,
Feb 22, 2014, 3:05:44 PM2/22/14
to rubyonra...@googlegroups.com
Hello,

MyModel.rb,

TYPES = { "type1" => 1 , "type2" => 2, "type3" => 3 }.freeze
validates_inclusion_of :my_type, :in => TYPES.keys

---------------------------------------
MyModelPatch.rb,

base.send(:remove_const, :TYPES)
base._validators[:my_type].reject!{ |validator| validator if
validator.is_a? ActiveModel::Validations::InclusionValidator }

TYPES = { "type1" => 1 , "type2" => 2, "type3" => 3,"type4" => 4,
"type5" => 5 }.freeze
base.const_set('TYPES',TYPES)
base.class_eval do
validates_inclusion_of :my_type, :in => TYPES.keys
end

----------------------------------------

In my View or Console, The MyModel::TYPES gives me the patched hash, But
saving the patched model with the new types failes. With the error "is
not included in the list"

Please help me, As I am not able to figure out what wrong I have done,
And am I missing something.

Thank You,

Best Regards,
Rupesh

--
Posted via http://www.ruby-forum.com/.

Matt Jones

unread,
Feb 23, 2014, 5:36:17 PM2/23/14
to rubyonra...@googlegroups.com
The _validations attribute is kept in sync by the various macros (validates_* and validates itself), but it is NOT the mechanism used to actually do the validation - that's handed off to the callbacks stuff (which also handles :on, :if, and :unless criteria).

This post seems closer to what you're intending:


But I'd recommend thinking more about what the intent actually is - if you're trying to override the list of possible types in a subclass, it would make more sense to have an explicit validator that *asks* the class for the correct set of types to be used.

--Matt Jones

Rupesh Jayaprakash

unread,
Feb 23, 2014, 9:36:38 PM2/23/14
to rubyonra...@googlegroups.com
Thank You Matt. I was not aware of this. This helped me solve my
problem.
The "sub class" idea is a good one, did not occur to me at all. :-(
Reply all
Reply to author
Forward
0 new messages