Automatically creating validates for limitable columns by releu
When I have got a PG::Error: ERROR: value too long for type character varying(255) error I wondered how to solve this problem globally.
Then I created a #concern which creates validations for all string-columns.
module Models
module Limitable
extend ActiveSupport::Concern
included do
columns.each do |column|
case column.type
when :string then
validates column.name, length: { maximum: column.limit }
end
end
end
end
end
class User
include Models::Limitable
end
Thats it! Very simple.
Comments
zaadjis commented 9 months ago
Or just use https://github.com/lomba/schema_validations!
releu commented 9 months ago
Thanks! Nice gem
ndbroadbent commented 9 months ago
Great stuff, I always thought it would make much more sense if this was automatic.