从rails中恢复失败模型的最佳方法

时间:2015-09-23 04:27:45

标签: ruby-on-rails ruby error-handling rails-activerecord

我有一些代码可以从twitter API获取一些推文:

initial_tweets = get_tweets_in_time_range self.name, (Time.now-1.weeks), Time.now 

initial_tweets.each do |tweet|
    new_tweet = Tweet.new

    new_tweet.favorite_count = tweet.favorite_count 
    new_tweet.filter_level = tweet.filter_level 
    new_tweet.retweet_count = tweet.retweet_count 
    new_tweet.text = tweet.text 
    new_tweet.tweeted_at = tweet.created_at 

    new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z' 

    new_tweet.save 
    # What happens on a failed save
end

如果保存失败,那么正确的后备是什么?正如评论所指出的那样。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

save只返回true或false,您可以使用save!,如果记录无效,它将引发异常。如果异常提出,你可以抓住它。

begin
  ....
  new_tweet.save!
rescue exception => e
  puts e.inspect
  #you can continue the loop or exit
end

正如@Stefan所说,你可以将代码包装在一个事务中,如果一个记录保存失败,所有保存的记录都将回滚。除非你真的希望每条记录都能成功,否则我不建议你这样做。

Tweet.transaction do
   initial_tweets = get_tweets_in_time_range self.name, (Time.now-1.weeks), Time.now 
initial_tweets.each do |tweet|
    new_tweet = Tweet.new
    ..... 
    new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z' 

    new_tweet.save! # you have to add '!', once save failed, it will trigger rolls back.
  end
end