简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM