2013-10-07 45 views
2

我想弄清楚爲使用地理編碼器的導軌4應用驗證錯誤。驗證與地理編碼器寶石

我的模型看起來是這樣的:

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解釋說我應該使用before_validation而不是after_validation,但我仍然不明白在哪裏添加錯誤,以便我的視圖可以重新呈現並且可以輸入有效的地理位置。

任何想法,我應該把這些信息? 謝謝!

回答

0

試着這麼做:

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

這並不是因爲工作,如果在數據庫中的地址沒有被輸入的是,病情'驗證:地址,存在:TRUE'總是會因爲地址被通過地理編碼後產生的返回一個錯誤發出API請求。 – DaniG2k

+0

,所以地理編碼應在驗證前提出請求。這就是爲什麼在那裏有一個before_validation ... –

1

您可以在模型中設置這樣下面的例子來驗證地址時,地址改變了地理編碼將被調用一次。在geocoded_by方法中,我們明確地設置了寫入經度和緯度,因此比找不到地址的列將被設置爲零。

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