Search code examples
ruby-on-railsformsvalidationdevisesimple-form

Rails: Simple-Form & Devise: mark email field of user model as required in forms automatically?


I wonder why the field email is not marked as a required field in Simple-Form, as when submitting it empty there is a validation error "can't be blank".

screenshot

It seems that the validation rules for the email field come from Devise, so they are available to the validation mechanism, but not to Simple-Form. Why's that?

I could simply add another validates :email, presence: true to my User model, but this seems overkill. Or I could add a required: true to the f.input :email method of Simple-Form, but this seems like overkill, too.

Here's the relevant part of my User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, authentication_keys: [:login]

  validates :name, presence: true

Do I have something configured incorrect/incomplete?


Solution

  • From Simple Form's README:

    For performance reasons, this detection is skipped on validations that make use of conditional options, such as :if and :unless.

    And you can see that Devise will add validation with an :if in https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb

        base.class_eval do
          validates_presence_of   :email, if: :email_required?
          validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
          validates_format_of     :email, with: email_regexp, allow_blank: true, if: :email_changed?
    
          validates_presence_of     :password, if: :password_required?
          validates_confirmation_of :password, if: :password_required?
          validates_length_of       :password, within: password_length, allow_blank: true
        end
    

    So you have to mark the field as required in your views.