복붙노트

[RUBY-ON-RAILS] 3.1 제한 사용자가 만든 개체 레일

RUBY-ON-RAILS

3.1 제한 사용자가 만든 개체 레일

나는 사용자가 만들 수 있습니다 모델 객체의 수를 제한하고 싶습니다. 나는 아래를 해봤지만 작동하지 않습니다. 나는 몇 가지 변화가 레일 3.1에서 발생하고하지 않도록 지금이 작업을 수행하는 방법을 이해합니다.

class User < ActiveRecord::Base
  has_many :things, :limit => 5, :dependent => :destroy # This doesn't work
end

class Things <ActiveRecord::Base
  belongs_to :user
end

해결법

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

    1.이 같은 시도 :

    이 같은 시도 :

    class User < ActiveRecord::Base
      has_many :things
    end
    
    class Things <ActiveRecord::Base
      belongs_to :user
      validate :thing_count_within_limit, :on => :create
    
      def thing_count_within_limit
        if self.user.things(:reload).count >= 5
          errors.add(:base, "Exceeded thing limit")
        end
      end
    end
    

    편집 : 레일 업데이트 3

  2. ==============================

    2.그것은 레일 3.2.1에서 작동하지 않았다. 항상 내가 self.user.things.size로 교체 한 0으로 동일 지금 작동 계산합니다.

    그것은 레일 3.2.1에서 작동하지 않았다. 항상 내가 self.user.things.size로 교체 한 0으로 동일 지금 작동 계산합니다.

  3. from https://stackoverflow.com/questions/7863618/rails-3-1-limit-user-created-objects by cc-by-sa and MIT license