LuanDantas
5/27/2018 - 2:32 AM

Validações especiais (Concerns)

Basicamente são modelos com métodos reaproveitáveis. A seguir, criaremos um concern que verifica se existe mais de um filme com highlightable. Caso exista, faremos uma tratativa, pois só podemos ter um filme/série com a flag de highlight.

Validações Especiais (concerns)

module Highlightable
  extend ActiveSupport::Concern
  
  include do
    validate :single_highlight

    def single_highlight
      any_entity = has_any_other_highlighted?(Movie)
      any_entity ||= has_any_other_highlighted?(Serie) unless any_entity
      if highlighted && any_entity
        errors.add(:single_highlight, "Only one highlighted entity is permitted")
      end
    end

    def has_any_other_highlighted?(model)
      records = model.where(highlighted: true)
      if self.class == model
        return records.where.not(id: self.id).any?
      end
      records.any?
    end
  end
end

Para utilizar esse concern nos modelos, basta incluí-lo da seguinte maneira:

class Serie < ApplicationRecord
  include Highlightable
end