지오 코더를 사용하는 레일 4 앱에 유효성 검사를위한 오류를 추가 할 위치를 파악하려고합니다.지오 코더 gem을 사용한 유효성 검사
내 모델은 다음과 같습니다
class Tutor < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
geocoded_by :address do |obj, results|
if geo = results.first
obj.latitude = geo.latitude
obj.longitude = geo.longitude
obj.country = geo.country
obj.city = geo.city
obj.postalcode = geo.postal_code
obj.address = geo.address
end
end
after_validation :geocode, if: :address_changed?
end
나는 주소가 성공적으로 발견 된 경우 조건부 if geo = result.first
만 실행됩니다 것으로 나타났습니다. nil 반환되는 경우 오류 메시지를 추가하고 싶습니다. 나는 this stackoverflow thread이 after_validation
대신에 before_validation
을 사용해야한다고 설명했으나 여전히 내 뷰가 렌더링되고 올바른 geolocation을 입력 할 수 있도록 오류를 추가하는 위치를 이해하지 못합니다.
이 정보를 넣어야하는 아이디어는 무엇입니까? 감사합니다. 당신은 주소가 변경 될 때 지오는 한 번만 호출됩니다 주소를 확인하기 위해 아래의 예와 같이 모델에 설정할 수 있습니다
class Tutor < ActiveRecord::Base
belongs_to :user
before_validation :geocode, if: :address_changed?
validates :user_id, :address, presence: true
geocoded_by :address do |obj, results|
if geo = results.first
obj.latitude = geo.latitude
obj.longitude = geo.longitude
obj.country = geo.country
obj.city = geo.city
obj.postalcode = geo.postal_code
obj.address = geo.address
else
obj.address = nil
end
end
end
이 때문에 작동하지 않습니다 주소가 아직 데이터베이스에 입력되지 않은 경우, 조건은'유효성을 검사 : 주소가 존재 : 주소가 뒤에 지오 코더에 의해 생성됩니다 때문에 TRUE '는 항상 오류를 반환합니다 API 요청을합니다. – DaniG2k
이므로 지오 코딩 된 데이터는 유효성 검사 전에 요청해야합니다. 그곳에 before_validation이있는 이유는 ... –