이것은 견과류입니다. 내가 초기화와 같은 수준의 아이들의 유효성을 검사 죽은 간단한 콜백 함수가 : 지금까지레일 ActiveRecord 콜백 엉망
a = A.new
>>[#<A>]
a.bs
>> [#<T>]
a.save
>> true
a.id
>> 15
을 그것은 모두가 좋은 것, 그러나이다 :
class A < ActiveRecord::Base
has_many :bs
after_initialize :add_t_instance
validate :has_only_one_t
protected
def add_t_instance
bs << B.new(:a => self, :type => "T") unless bs.map(&:type).count("T") > 0
end
def has_only_one_t
unless bs.map(&:type).count("T") < 2
errors.add(:bs, 'has too many Ts")
end
end
end
지금을, 여기 런타임에 마법을 제공 :
s = A.find(15)
s.bs
>>[#<T>,#<T>]
s.bs.count
>> 2
s.valid?
>> false
s.errors.full_messages
>> "Too many Ts"
여기에 실종 된 것은 무엇입니까?!?! 세계에서 두 번째 #T를 추가 할 수있는 것은 무엇입니까?
이 작업을 다시 시도했지만 하위 클래스 'T'가 정의되지 않았기 때문에 'A'개체를 다시로드하려고하면 오류가 발생합니다. 레일스는 컬럼 이름 'type'때문에 규칙에 따라 서브 클래스를 감지하려고합니다. 'T'에 대한 클래스 정의가 있습니까? – PinnyM
예. 아무 문제 없어. – muichkine