3

我正在尝试找出在哪里为使用地理编码器的 rails 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,我想添加一条错误消息。我看到这个 stackoverflow 线程解释说我应该使用before_validation而不是after_validation,但我仍然不明白在哪里添加错误,以便我的视图可以重新渲染并可以输入有效的地理位置。

有什么想法我应该把这些信息放在哪里?谢谢!

4

2 回答 2

2

您可以像下面的示例一样在模型中设置以验证地址,地址更改时仅调用一次地理编码。在 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
于 2017-03-15T16:18:14.887 回答
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
于 2013-10-08T08:55:19.027 回答