How to set non-zero restriction 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 to set a NOT NULL header? 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 this query into ActiveRecord?

+4
source share
2 answers

To set a non-zero restriction at the database level, add null: falseActiveRecord to the 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 that works at the Rails level and provides error messages to end users:

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

. Rails Guides .

+4

t.string :title

t.string  :title, null: false
+1

Source: https://habr.com/ru/post/1524554/


All Articles