Ruby on rails 如何在迁移文件(Rails 4)中添加验证
我正在尝试在数据库级别添加验证。对于模型文件来说没有问题,但是现在对于迁移文件,我不知道怎么做。我正在使用SQLite进行开发(遵循Hartl的教程,但修改了我自己应用程序的说明) 我有以下两个迁移文件:Ruby on rails 如何在迁移文件(Rails 4)中添加验证,ruby-on-rails,ruby-on-rails-4,sqlite,Ruby On Rails,Ruby On Rails 4,Sqlite,我正在尝试在数据库级别添加验证。对于模型文件来说没有问题,但是现在对于迁移文件,我不知道怎么做。我正在使用SQLite进行开发(遵循Hartl的教程,但修改了我自己应用程序的说明) 我有以下两个迁移文件: class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :email, null: false t.s
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email, null: false
t.string :email_confirm, null: false
t.string :username, null: false
t.text :bio
t.string :location, null: false
t.boolean :activated, default: false
t.datetime :activated_at
t.timestamps null: false
end
end
end
因此null:false
和default:false
不在schema.rb中,显然Rails没有实现这些验证。我应该如何在迁移文件中实现这些验证
我也尝试过使用
change\u column\u null
和change\u column\u default
,但结果相同/schema.rb。Rails允许您在迁移中为列提供null
和default
选项
编辑用户迁移文件后,是否重新运行该文件
您可以先执行rakedb:rollback
,然后执行rakedb:migrate
如果您最后运行了
CreateUsers
和AddIndexToUsersEmailAndUsername
,您应该使用两个步骤执行回滚,如rake db:rollback STEP=2
运行迁移后您是否编辑了迁移?我已经完成了bundle exec rake db:reset
和bundle exec rake db:migrate
。我想这比回滚还要好。。。?所以这应该不是问题。我尝试了bundle exec-rake-db:migrate VERSION=0
,然后bundle exec-rake-db:migrate
。这成功了!Schema.rb现在确实包括null
和default
选项。
class AddIndexToUsersEmailAndUsername < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
add_index :users, :username, unique: true
end
end
ActiveRecord::Schema.define(version: 20150410200022) do
create_table "Users", force: :cascade do |t|
t.string "email"
t.string "email_confirm"
t.string "username"
t.text "bio"
t.string "location"
t.boolean "activated"
t.datetime "activated_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["username"], name: "index_users_on_username", unique: true
end