[Proposal] Rails model generator: validating presence by default

Hi all,

We all should know the importance of validations. However, it’s so easy to forget to add validations at first and some time later we notice that it’s too late.

I’d like to propose that adding presence validation for all generated columns. For example,

rails g model Post title body deleted_at

it generates

class Post
  validates :title, presence: true
  validates :body, presence: true
  validates :deleted_at, presence: true
end

Notice that deleted_at can be nil, so we need to remove that line. The point is that failing to add the validations that should exist is crucial so adding them worth removing them manually, and presence validation is the most typical case.

I know some say it’s too much, but there’s a tendency to be reluctant to change generated code, or just to forget modifying, so changing generated code could have values. After all, removing validations is easier than adding them.

I would suggest adding presence validations only if we specify not null for columns.

1 Like

Validating presence by default is a good practice, but I don’t think generators are the right place to implement it. For example, if a developer adds an attribute by manually editing a migration script – thus bypassing rails g – the corresponding model.rb file would not be updated.

I’d suggest a custom validator that iterates over ActiveRecord#attributes to check for nil values. Optional attributes could be identified by a method in the validator, similar in spirit to skip_before_action. Invoke the custom validator in application_record.rb and you’re all done.

Something like this could be packaged as a gem pretty easily.