我正在尝试找出将验证错误添加到使用地理编码器的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,我想添加一条错误消息。我看到this stackoverflow thread解释说我应该使用before_validation
而不是after_validation
,但我仍然不明白添加错误的位置,以便我的视图可以重新呈现并且有效地理位置可以输入。
我应该提供这些信息的任何想法? 谢谢!
答案 0 :(得分:1)
您可以在下面的示例中设置模型以验证地址更改时地址将仅被调用一次的地址。在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
答案 1 :(得分: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