简体   繁体   中英

Ruby on Rails: Is it better to validate in the model or the database?

Is it generally better practice (and why) to validate attributes in the model or in the database definition?

For (a trivial) example:

In the user model:

validates_presence_of :name

versus in the migration:

t.string :name, :null => false 

On the one hand, including it in the database seems more of a guarantee against any type of bad data sneaking in. On the other hand, including it in the model makes things more transparent and easier to understand by grouping it in the code with the rest of the validations. I also considered doing both, but this seems both un-DRY and less maintainable.

I would highly recommend doing it in both places. Doing it in the model saves you a database query (possibly across the network) that will essentially error out, and doing it in the database guarantees data consistency.

And also

validates_presence_of :name

not the same to

t.string :name, :null => false 

If you just set NOT NULL column in your DB you still can insert blank value (""). If you're using model validates_presence_of - you can't.

It is good practice to do both. Model Validation is user friendly while database validation adds a last resort component which hardens your code and reveals missing validitions in your application logic.

It varies. I think that simple, data-related validation (such as string lengths, field constraints, etc...) should be done in the database. Any validation that is following some business rules should be done in the model.

I would recommend Migration Validators project ( https://rubygems.org/gems/mv-core ) to define validation on db level and then transparently promote it to ActiveRecord model.

Example:

in migration:

def change
  create_table :posts do |t|
    t.string :title, length: 1..30
  end 
end

in your model:

class Post < ActiveRecord::Base
  enforce_migration_validations
end

As result you will have two level data validation. The first one will be implemented in db ( as condition in trigger of check constraint ) and the second one as ActiveModel validation in your model.

取决于您的应用程序设计,如果您有一个中小型应用程序,您可以在两者中或仅在模型中执行它,但如果您有一个大型应用程序可能是面向服务或层次,那么具有基本验证,即强制/可空,数据库中的最小/最大长度等,更严格,即模型中的模式或业务规则。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM