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?
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 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.
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.
Change your t.string :title
line to
t.string :title, null: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With