2
Nmeri17
2y

Why does rails have validation at the model layer? Isn't that what the table schema/migration is for?

Comments
  • 1
    Only God knows

    and DHH...
  • 0
  • 2
    Database constraints are nice for some consistency guarantees but do not replace validation. First of all you place business logic in the persistent layer. Error handling (reporting) becomes depended on specific database technology used.

    Some validations are context based. The database must than allow for the least constrictive. For example only admin users may set an enum field to verified. The database should contain that value in the enum field even though other users should fail to set it so.

    A lot of validations are (near) impossible to put into constraints.
    For example this table:
    |id|version|name|email|
    We can't set a unique constraint on the email column because multiple versions of the id must allow it. Also in the history of another user the email may exist and that is fine but we don't want the same email in the latest version of any other user than we are currently saving.
  • 1
    Two reasons.

    It's faster to test a change like that inside the model. Migrations have a way of taking a long time on tables with a lot of data.

    It's more risky to run a migration that it is to change code. Yes, you should have backups. But lost time is gone forever.
Add Comment