How do you set a not null constraint in activerecord for ruby?

activerecord, ruby-on-rails

Solution

To set a non-null constraint at the database level, add `null: false` to the ActiveRecord migration. For example,

class CreatePosts < ActiveRecord::Migration
  def change
     create_table :posts do |t|
      t.string  :title,   null: false
      t.string  :content, null: false
      t.string  :author,  null: false
      t.timestamps
    end
  end
end

You should also (or can alternatively) add a presence validator to your model, which operates at the Rails level and provides informative error messages to your end-users:

class Post < ActiveRecord::Base
  validates :title, :content, :author, presence: true
end

see the Rails Guides on presence validation for more.

Problem

I have a migration that looks like this: ``` class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.string :content t.string :author t.timestamps end end end ``` How do I set title to be NOT NULL? If it were an SQL query, I would do it like this: ``` CREATE TABLE "posts" ("id" serial primary key, "title" character varying(255) NOT NULL, "content" character varying(255), "author" character varying(255), "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL) ``` So how do I translate that query into ActiveRecord?

Original source