Helpers in Ruby on Rails

numericality

This helper validates that your attributes only have numeric values. By default, this will match the possible sign of the first character, followed by an integer or floating point number. To specify that only integer values ​​are allowed, set :only_integer to true.

If you set :only_integer to true then the regular expression will be used

/\A[+-]?\d+\z/

to validate the attribute value. Otherwise, it will try to convert the value to a number using Float.

classPlayer<ApplicationRecord

  validates :points, numericality: true

  validates :games_played, numericality: { only_integer: true }

end

In addition to :only_integer , the validates_numericality_of helper also accepts the following options to add restrictions to valid values:

:greater_than – Specifies that the value must be greater than the value of the option. The default error message for this option is “must be greater than %{count}”.

:greater_than_or_equal_to – Specifies that the value must be greater than or equal to the value of the option. The default error message for this option is “must be greater than or equal to %{count}”.

:equal_to – Specifies that the value must be equal to the value of the option. The default error message for this option is “must be equal to %{count}”.

:less_than – Specifies that the value must be less than the value of the option. The default error message for this option is “must be less than %{count}”.

:less_than_or_equal_to – Specifies that the value must be less than or equal to the value of the option. The default error message for this option is “must be less than or equal to %{count}”.

:other_than – Specifies that the value must be different from the presented value. The default error message for this option is “must be other than %{count}”.

:odd – Specifies that the value should be odd if set to true. The default error message for this option is “must be odd”.

:even – Specifies that the value must be even if set to true. The default error message for this option is “must be even”.

NOTE: Numerity does not allow nil by default. To allow them, you can use the option allow_nil: true.

The default error message is “is not a number”.

presence

This helper validates that certain attributes are not empty. Does it use the blank method? to check if a value is either nil or an empty string (a string that is either empty or contains spaces).

classPerson < ApplicationRecord

  validates :name, :login, :email, presence: true

end

If you want to be sure that a relationship exists, you need to check if the related object itself exists, not the foreign key used for the relationship.

class LineItem < ApplicationRecord

  belongs_to :order

  validates :order, presence: true

end

In order to check for related records whose presence is needed, you need to define the :inverse_of option for the link:

classOrder < ApplicationRecord

  has_many :line_items, inverse_of: :order

end

When validating the existence of an object associated with a has_one or has_many relationship, it will check that the object is neither blank? nor marked_for_destruction?.

So how is false.blank? is true, if you want to validate the existence of a boolean field, you must use one of the following validations:

validates :boolean_field_name, inclusion: { in: [true, false] }

validates :boolean_field_name, exclusion: { in: [nil] }

When using one of these validations, you can be sure that the value will not be nil, which in most cases will convert to a NULL value.

absence

This helper checks that the specified attributes are missing. Does it use the present? to check that the value is either nil or the empty string (that is, either zero length or consisting of spaces).

classPerson < ApplicationRecord

  validates :name, :login, :email, absence: true

end

If you want to make sure that there is no relationship, you need to check that the related entity itself is missing, not the foreign key used for the relationship.

class LineItem < ApplicationRecord

  belongs_to :order

  validates :order, absence: true

end

To check for related objects that you want to be missing, you need to specify the :inverse_of option for the link:

classOrder < ApplicationRecord

  has_many :line_items, inverse_of: :order

end

If you are checking for the absence of an object associated with a has_one or has_many relationship, it will check that the object is neither present? nor marked_for_destruction?.

Because false.present? is false, if you want to check for the absence of a boolean field, you should use validates :field_name, exclusion: { in: [true, false] }.

The default error message is “must be blank”.

uniqueness

This helper validates that an attribute’s value is unique before the object is saved. It does not create a uniqueness condition in the database, hence it can happen that two different database connections will create two records with the same value for a column you think is unique. To avoid this, you need to create a unique index on both columns in your database.

class Account < ApplicationRecord

  validates :email, uniqueness: true

end

Validation is done by SQL querying the model table, searching for an existing record with the same attribute value.

There is a :scope option that can be used to define one or more attributes used to limit the uniqueness check:

class Holiday < ApplicationRecord

  validates :name, uniqueness: { scope: :year,

    message: “should happen once per year” }

end

If you want to create a database-level constraint to prevent possible uniqueness validation violations with the :scope option, you must create a uniqueness index on both database columns. For more information about multi-column indexes, see the MySQL manual, or examples of unique constraints related to a group of columns in the PostgreSQL manual.

There is also a :case_sensitive option that can be used to specify whether the unique constraint is case sensitive or not. The default option is true.

classPerson < ApplicationRecord

  validates :name, uniqueness: { case_sensitive: false }

end

WARNING. Note that some databases are configured to do case-sensitive searches anyway.

The default error message is “has already been taken”.

validates_with

This helper passes the entry to a separate class for validation.

class GoodnessValidator < ActiveModel::Validator

  def validate(record)

    if record.first_name == “Evil”

      record.errors[:base] << “This person is evil”

    end

  end

end

classPerson < ApplicationRecord

  validates_with GoodnessValidator

end

NOTE: Errors added to record.errors[:base] refer to the state of the record as a whole, not to a particular attribute.

The validates_with helper accepts a class or list of classes to use in validation. There is no default error message for validates_with. You must manually add errors to the errors collection of an entry in the validator class.

In order to use the validate method, it is necessary to have the record parameter defined, which is the record being validated.

Like all other validations, validates_with accepts :if , :unless and :on options. If you pass any other options, they will be passed to the validator class as options:

class GoodnessValidator < ActiveModel::Validator

  def validate(record)

    if options[:fields].any?{|field| record.send(field) == “Evil” }

      record.errors[:base] << “This person is evil”

    end

Leave a Reply

Your email address will not be published.