josias
josias

Reputation: 83

Where do I put the database constraints in rails?

Simple problem. I'm learning RoR. I swear that I searched this theme here and in google.

I need a lot of tables in my app.

I'm reading about the benefits of database constraints. I'm using validations inside every model, example:

class Example < ActiveRecord::Base

  belongs_to :other
  has_one :another...

  attr_accessible :username, :email, :password

  validates :username, e:mail, :password, presence: true
  validades .....
end

I would like to know about database constraints, how can i get the same validation inside the database? Should i put this constraints (like :null => false) inside the schema.rb file?

Upvotes: 2

Views: 335

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32748

Yes, absolutely put that in your migration:

:null => false

To require a non-empty field. Although an empty string can still be supplied and it passes the non-NULL test. You can cover this by adding a length validation:

validates_length_of :username, :minimum => 1, :maximum => 255

Upvotes: 1

Related Questions