如何在activeyord中为ruby设置一个非空约束?

Tar*_*oys 7 activerecord ruby-on-rails

我的迁移看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

如何将标题设置为NOT NULL?如果是SQL查询,我会这样做:

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) 
Run Code Online (Sandbox Code Playgroud)

那么如何将该查询转换为ActiveRecord?

Jak*_*mer 9

要在数据库级别设置非空约束,请添加null: false到ActiveRecord迁移.例如,

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
Run Code Online (Sandbox Code Playgroud)

您还应该(或者可以选择)向您的模型添加状态验证器,该模型在Rails级别运行并向最终用户提供信息性错误消息:

class Post < ActiveRecord::Base
  validates :title, :content, :author, presence: true
end
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅有关状态验证Rails指南.


Log*_*man 1

将您的t.string :title线路更改为

t.string  :title, null: false
Run Code Online (Sandbox Code Playgroud)