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

 小谢blue 发布于 2023-01-30 12:44

我的迁移看起来像这样:

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

如何将标题设置为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) 

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

1 个回答
  • 要在数据库级别设置非空约束,请添加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
    

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

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

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

    2023-01-30 12:47 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有