0
사람이 has_many 전화를 사용하는 단순한 관계가 주어졌습니다. 전화에는 고유해야하는 전화 번호 만 들어 있습니다!레일스는 belongs_to 관계를 확인합니다.
class Telephone < ActiveRecord::Base
validates_presence_of :contact_id
belongs_to :contact
validates :telephone, {:presence => true, :uniqueness => true}
end
class Contact < ActiveRecord::Base
has_many :telephones
validates_associated :telephones
has_many :emails
has_many :addresses
validates_presence_of :firstname
accepts_nested_attributes_for :telephones, :allow_destroy=>true
validates_presence_of :lastname
end
test "telephone number must be unique" do
john = contacts :johndoe #johndoe is a person with 1 existing number
2.times do
john.telephones.build :telephone=> "123" # 123 doesnt exist yet
end
puts Telephone.count # this gives 1
john.save
puts Telephone.count # this gives 3 !!!! ???
assert not(john.valid?) # This validates unless I remove the save above
end
누군가이 테스트의 결과를 설명 할 수 있습니까?
- 그냥 유효합니까? 실패하지만 rdoc에 언급되어 있음 (먼저 저장해야 함)
- 먼저 저장하면 유효합니까? 패스
BUT 이제 데이터베이스에는 실제로 고유 한 요구 사항을 위반하는 레코드가 3 개 있습니다.
더 좋은 방법이 있나요? 나는이 시험의 결과를 이해하지 못한다. 그것은 정말로 내 기대에 어긋난다.
답변으로 받아 들일 것입니다. DB를 무겁게 여기는 것이 좋을 것 같습니다. 하지만 공정하게 말하면, 문서에는 2 단계 프로세스 문제가 언급되어 있습니다. – npiv