我的迁移看起来像这样:
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指南.