Kamal G'ool
Kamal G'ool

Reputation: 171

creating a new column datatype in rails

I might have not been searching for the right words in order to get an answer, so you were my last chance.

I am looking to create a new datatype in rails, for example: t.israeli_id

which gets to pass a customized validation method, and adds errors according to it.

I will be using this datatype in several tables, so making it a string, and passing the validation function in each model.rb would be so much not DRY.

I am using Postgresql, just in case that would matter.

Upvotes: 0

Views: 72

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

Nope, you are approaching this in a wrong way. Database knows nothing about your application logic and it can only do basic validation (not null, etc.).

All of your application-specific validation, error messages and other stuff - it goes into your model. If you need that in several models and don't want duplicating the code, then create a model concern, HasIsraeliId or something. That's what concerns are for.

# app/models/concerns/has_israeli_id.rb
module HasIsraeliId
  extend ActiveSupport::Concern

  included do
    validate :some_field, whatever_condition: true
  end
end

# app/models/user.rb
class User < ApplicationRecord
  include HasIsraeliId
end

Upvotes: 1

Related Questions