ruby-on-rails – 如何在activeyord中为ruby设置一个非空约束?
发布时间:2020-12-17 03:32:01 所属栏目:百科 来源:网络整理
导读:我的迁移看起来像这样: class CreatePosts ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.string :content t.string :author t.timestamps end endend 如何将标题设置为NOT NULL?如果是SQL查询,我会这样做: CREATE T
我的迁移看起来像这样:
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? 解决方法
要在数据库级别设置非空约束,请将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 Guides on presence validation了解更多信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |