26

2020-04-07-yil-rails-validators-dont-change-type

 4 years ago
source link: https://github.com/tamouse/swaac/blob/master/posts/2020/04/2020-04-07-yil-rails-validators-dont-change-type.md
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
title date category tags

YIL: Rails validators don't change parameter type

2020-04-07T09:04

rails

validation

type

params

So I figured this out a while ago, but seems that I forgot to write it down, hence "YIL" - Yesterday I Learned.

I was working with a numeric parameter in Rails, that needed to be a non-negative interger, less than a maximum level. A pretty simple validator :

validates_numericality_of :age,
                          :only_integer,
                          greater_than_or_equal_to: 0,
                          less_than_or_equal_to: MAX_AGE

The validators work with age regardless of whether it's a number or string; coming in via a parameter from the controller, it will be a string. In a Rails model, this isn't much of an issue since the variable gets converted to whatever is the right type when the record is persisted.

The case I was working with wasn't an ActiveRecord however, but just an ActiveModel service object.

In order to fix this for the object model, I used an after_validation callback to transform the variable:

def recast_attributes

  age = age.to_i

end

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK