How do I force a rails ActiveRecord string column to only accept strings? -
i have post
class title:string
field
post = post.create! #=> post created post.title = "foo" post.save! # success post.title = 1 post.save! # succeeds, want throw type mismatch exception
how last save! throw type mismatch?
ruby duck-typed language , doesn't have type mismatches. if object responds to_s
, rails call to_s
on , put string field.
it sounds want validate format of value you're putting field (is string "2"
valid value?), validates_format_of
for. example, if want ensure value has @ least 1 non-digit character, this:
class post < activerecord::base validates_format_of :title, with: /\d/ end
of course, may want customize regex bit more.
if can't stand duck-typing , want make sure nothing true string goes column, can override title=
:
class post < activerecord::base def title=(value) throw "`title' must string" unless value.is_a?(string) super end end
note won't invoked when e.g. post[:title] = ...
or post.write_attribute(:title, ...)
should cover 95% of situations.
Comments
Post a Comment