복붙노트

[RUBY-ON-RAILS] 루비 온 레일즈에 has_many 항목의 수의 유효성을 검사합니다

RUBY-ON-RAILS

루비 온 레일즈에 has_many 항목의 수의 유효성을 검사합니다

사용자는 조각에 태그를 추가 할 수 있습니다 :

class Snippet < ActiveRecord::Base

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

end

6. 대부분에서 어떻게이 작업을 수행하는 대한 생각, 적어도 1 : 나는 태그의 수를 확인하려면? 감사.

해결법

  1. ==============================

    1.당신은 항상 사용자 지정 유효성 검사를 생성 할 수 있습니다.

    당신은 항상 사용자 지정 유효성 검사를 생성 할 수 있습니다.

    같은 뭔가

      validate :validate_tags
    
      def validate_tags
        errors.add(:tags, "too much") if tags.size > 5
      end
    
  2. ==============================

    2.더 나은 솔루션이 SO 게시물에 @SooDesuNe에 의해 제공되었다

    더 나은 솔루션이 SO 게시물에 @SooDesuNe에 의해 제공되었다

    validates :tags, length: { minimum: 1, maximum: 6 }
    
  3. ==============================

    3.난 당신이 .reject 사용하여 유효성을 검사 할 수 있습니다 생각 (? marked_for_destruction를) 길이를..

    난 당신이 .reject 사용하여 유효성을 검사 할 수 있습니다 생각 (? marked_for_destruction를) 길이를..

    이건 어때?

    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
    

    아니면 이거.

    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
    

    그런 다음 명령 할 수있다.

    @user.assign_attributes(params[:user])
    @user.valid?
    

    읽어 주셔서 감사합니다.

    참고 :

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

  4. from https://stackoverflow.com/questions/4836897/validate-the-number-of-has-many-items-in-ruby-on-rails by cc-by-sa and MIT license