我有一个看起来像这样的迁移:
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约束,请将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。
关于ruby-on-rails - 如何在ActiveRecord中为ruby设置非null约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21462888/