ActiveRecord 유효성 검사 내의 an : if 절이 존중되지 않는 문제가 있습니다.이유 : ActiveRecord 유효성 검사에서 인식되지 않는 이유는 무엇입니까?
내 모델에는 존재하는 것으로 숫자를 확인하고 특정 범위 내에서 유효성을 검사하는 ip_port 속성이 있습니다. 각 조건이 하나의 오류 만 생성하도록 보장하려고합니다. 나는 빈 속성이 사용자에게 3 개의 메시지를 표시하여 그것이 존재하지 않고 필요하며 숫자가 아니라는 것을 나타내는 상황을 원하지 않는다. 이
class Arc < ActiveRecord::Base
attr_accessible :ip_port
validates_presence_of :ip_port
validates_numericality_of :ip_port, :allow_blank => true
validates_inclusion_of :ip_port, :in => 1025..65535, :allow_blank => true,
:if => Proc.new {|arc| arc.ip_port.to_s.match(/^\d+$/) }
end
스탠드 그리고 이것은 내 모델 사양과 그 결과를 그대로
이 내 모델입니다.
describe Arc do
it "should be valid with valid attributes" do
Arc.new(:ip_port => 1200).should be_valid
end
it "should be invalid with a non-numberic port" do
Arc.new(:ip_port => "test").should be_invalid
end
it "should be invalid with a missing port" do
Arc.new(:ip_port => nil).should be_invalid
end
it "should have one error with a missing port" do
a = Arc.new(:ip_port => nil)
a.should be_invalid
a.should have(1).errors_on(:ip_port)
end
it "should have one error with a non-numeric port" do
a = Arc.new(:ip_port => "test")
a.should be_invalid
a.should have(1).errors_on(:ip_port)
end
it "should have one error with a numeric port outside the range" do
a = Arc.new(:ip_port => 999)
a.should be_invalid
a.should have(1).errors_on(:ip_port)
end
end
Arc - should be valid with valid attributes - should be invalid with a non-numberic port - should be invalid with a missing port - should have one error with a missing port - should have one error with a non-numeric port (FAILED - 1) - should have one error with a numeric port outside the range 1) 'Arc should have one error with a non-numeric port' FAILED expected 1 errors on :ip_port, got 2 ./spec/models/arc_spec.rb:21: Finished in 0.108245 seconds
내 질문은 제가 숫자가 아닌 ip_port 두 가지 오류를 얻고있는 이유 인 경우 : 절이 호출되고에서의 validates_inclusion을 방지해야합니다. 루비 2.3.5 내가 내 자신의 문제를 해결 한 명상 산책을 가지는 동안/X 10.6.3
캐스팅하기 전에 값을 사용하고 있다면 여전히 to_s가 필요합니까? (당신이 틀 렸음을 말하는 것이 아니라 내 자신의 무지를 묻는 것) – Chowlett
@Chris. 네, 그렇습니다. ip_port 속성에 정수가 할당되면 Fixnum에서 일치가 실패하므로 유효성 검사가 실패합니다. –
아 물론, 이것은 * 데이터베이스에 쓰고 있기 때문입니다. * arc.ip_port를 사용할 때 * 왜 * 수치 검증이 시작됩니까? – Chowlett