2013-10-07 2 views
2

지오 코더를 사용하는 레일 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 threadafter_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 

답변

0

같은 것을보십시오. geocoded_by 메소드에서 주소를 찾을 수 없을 때보다 위도와 경도를 명시 적으로 설정하여 해당 열을 nil로 설정합니다.

class Company < ActiveRecord::Base 
    geocoded_by :address do |object, results| 
    if results.present? 
    object.latitude = results.first.latitude 
    object.longitude = results.first.longitude 
    else 
    object.latitude = nil 
    object.longitude = nil 
    end 
    end 

    before_validation :geocode, if: :address_changed? 

    validates :address, presence: true 
    validates :found_address_presence 

    def found_address_presence 
    if latitude.blank? || longitude.blank? 
     errors.add(:address, "We couldn't find the address") 
    end 
    end 
end 
+0

이 때문에 작동하지 않습니다 주소가 아직 데이터베이스에 입력되지 않은 경우, 조건은'유효성을 검사 : 주소가 존재 : 주소가 뒤에 지오 코더에 의해 생성됩니다 때문에 TRUE '는 항상 오류를 반환합니다 API 요청을합니다. – DaniG2k

+0

이므로 지오 코딩 된 데이터는 유효성 검사 전에 요청해야합니다. 그곳에 before_validation이있는 이유는 ... –