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.

#rails #activerecord

Similar posts

Comments

releu commented 9 months ago

757fb0d5ec7560b6f25f5bd98eadc020?size=52

Thanks! Nice gem

ndbroadbent commented 9 months ago

4931eceec58528529fd004e56af197c4?size=52

Great stuff, I always thought it would make much more sense if this was automatic.

ndbroadbent
releu
zaadjis