在我的联系人类中,在使用电子邮件地址创建联系人之后,我会尽可能地从FullContact的API中提取尽可能多的联系人数据。
我遇到了这样的问题:如果FullContact中的"person“不存在一列数据,它就会抛出一个NoMethodError,并且我无法将可能存在的其余数据保存到联系人中,因为我的方法会在出错时停止。
我如何才能从NoMethodError中拯救出来,让我的方法继续运行其余的呢?就像它跳过错误并尝试其他代码一样。我已经在我的救援代码中尝试过next和continue,但这是行不通的。
谢谢你的帮助。
class Contact < ActiveRecord::Base
belongs_to :user
after_create do |contact|
contact.delay.update_fullcontact_data
end
def update_fullcontact_data
person = FullContact.person(self.email)
if person.contact_info.given_name.present?
self.name = person.contact_info.given_name
end
if person.contact_info.family_name.present?
self.last_name = person.contact_info.family_name
end
if person.demographics.location_general.present?
self.city = person.demographics.location_general
end
save!
rescue NoMethodError => exception
puts "Hit a NoMethodError"
save!
end
end发布于 2015-06-01 17:58:31
通常,解决问题的方法是try方法(http://apidock.com/rails/Object/try)。为了简短起见,它返回零,而不是在特定对象上不存在方法时引发异常。
发布于 2015-06-01 19:01:07
如果您只想确保保存,可以使用ensure执行如下操作:
class Contact < ActiveRecord::Base
belongs_to :user
after_create do |contact|
contact.delay.update_fullcontact_data
end
def update_fullcontact_data
person = FullContact.person(self.email)
if person.contact_info.given_name.present?
self.name = person.contact_info.given_name
end
if person.contact_info.family_name.present?
self.last_name = person.contact_info.family_name
end
if person.demographics.location_general.present?
self.city = person.demographics.location_general
end
save!
ensure
save!
end
end更多信息:end.html
https://stackoverflow.com/questions/30580012
复制相似问题