可能重複:
Ruby on Rails: Is it better to validate in the model or the database?導軌:驗證模型VS遷移
我看到它有可能在兩個軌模型和遷移添加相同的約束/驗證。但哪一個是最好的方法?驗證模型和數據庫級別(以及爲什麼)是否是一種好的做法?或者他們在軌道上相同?
例如,我們可以對模型和遷移中的名稱進行相同的驗證
class User < ActiveRecord::Base
validates :name, :uniqueness => true, :presence => true
end
class CreateUser < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name, :unique => true, :null => false
end
end
end
好問題。我會說在模型中做它,並讓它強制執行到數據庫,但我有興趣聽到別人說什麼。 – ardochhigh