Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 847
Tara Roys Avatar asked Jan 30 '14 17:01

Tara Roys


People also ask

Is null false Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

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.

like image 60
Jake Romer Avatar answered Oct 14 '22 23:10

Jake Romer


Change your t.string :title line to

t.string  :title, null: false
like image 45
Logan Serman Avatar answered Oct 14 '22 22:10

Logan Serman