A. Bhujel
A. Bhujel

Reputation: 55

Model Validation from Migration - Ruby on Rails

Beginner in Ruby on Rails

I have tables in PostgreSql Database. I was able to dump the schema from the existing database to the Ruby schema and migrate it (Which made save like a lot of time for me)

Now I am wondering if there is a way to implement Model Validation from Migration Validation. I have data validations implemented on the fields of table. I want to implement same validations to the Model as well. Is there a way to do it with minimal codes or do I have to manually create validations in each model?

For eg:

create_table "corporates", id: :serial, force: :cascade do |t|
   t.string "corporate_no", limit: 13, null: false
   t.string "corporate_name", null: false
   t.boolean "active", default: true
   t.datetime "created_at"
   t.datetime "updated_at"
   t.index ["corporate_no"], name: "corporates_corporate_no_key", unique: true
end

Now I want to implement this validation in my model as

class Corporate < ApplicationRecord
   validates :corporate_no, presence: true, limit: 13
   validates :corporate_name, presence: true
   validates :active, default: true
end

P.S. Those Model Validations may be wrong. Did I say I was beginner?

Thank you!

Upvotes: 0

Views: 2297

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

It's unlikely that there's something out of the box in Rails.

But I've found a gem schema_validations which probably does, what you're looking for.

The only difference is that this gem follows DRY approach and doesn't generate validations in the model. For example, you have users table:

create_table :users do |t|
  t.string :email, null: false, limit: 30
  t.boolean :confirmed, null: false
end

This gem won't generate validations as you expect:

class User < ActiveRecord::Base
  validates :email, presence: true, length: { maximum: 30 }
  validates :confirmed, presence: true, inclusion: { in: [true, false] }
end

You're still going to have clean User model, but the fields are validated:

class User < ActiveRecord::Base
end

And it can be configured if you don't need validations on every model.

Upvotes: 1

Related Questions