Sprawdź liczbę ma wiele elementów w Ruby on Rails

Użytkownicy mogą dodawać tagi do fragmentu:

class Snippet < ActiveRecord::Base

  # Relationships
  has_many :taggings
  has_many :tags, :through => :taggings
  belongs_to :closing_reason

end

Chcę zweryfikować liczbę tagów: co najmniej 1, co najwyżej 6. Jak mam to zrobić? Dzięki.

Author: Nick, 2011-01-29

3 answers

Zawsze możesz utworzyć walidację niestandardową .

Coś jak

  validate :validate_tags

  def validate_tags
    errors.add(:tags, "too much") if tags.size > 5
  end
 68
Author: Nikita Rybak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-31 01:00:32

Lepsze rozwiązanie dostarczył @SooDesuNe on this so post

validates :tags, length: { minimum: 1, maximum: 6 }
 71
Author: sbonami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:08

Myślę, że możesz zweryfikować używając .reject(&:marked_for_destruction?).length.

Co ty na to?
class User < ActiveRecord::Base
  has_many :groups do
    def length
      reject(&:marked_for_destruction?).length
    end
  end
  accepts_nested_attributes_for :groups, allow_destroy: true
  validates :groups, length: { maximum: 5 }
end
Albo to.
class User < ActiveRecord::Base
  has_many :groups
  accepts_nested_attributes_for :groups, allow_destroy: true
  GROUPS_MAX_LENGTH = 5
  validate legth_of_groups

  def length_of_groups
    groups_length = 0
    if groups.exists?
      groups_length = groups.reject(&:marked_for_destruction?).length
    end
    errors.add(:groups, 'too many') if groups_length > GROUPS_MAX_LENGTH
  end
end

Wtedy możesz dowodzić.

@user.assign_attributes(params[:user])
@user.valid?
Dziękuję za przeczytanie.

Bibliografia:

Http://homeonrails.com/2012/10/validating-nested-associations-in-rails / http://qiita.com/asukiaaa/items/4797ce44c3ba7bd7a51f

 7
Author: asukiaaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-08 09:58:54