markdown Validaçõesespeciais(关注)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Validaçõesespeciais(关注)相关的知识,希望对你有一定的参考价值。

## Validações Especiais (concerns) ##

```ruby
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:

```ruby
class Serie < ApplicationRecord
  include Highlightable
end
```

以上是关于markdown Validaçõesespeciais(关注)的主要内容,如果未能解决你的问题,请参考以下文章