2012-02-01 13 views
1

我是Ruby和Ror的新手,所以任何指導都會很棒。我有一個函數:Ruby方式做失敗的數據庫保存

def self.insert_feed_product_scores(id, low, high) 
    avgScore = low.to_s + " - " + high.to_s 
    @feedProduct = FeedProduct.find(id) 
    @feedProduct.avg_score = avgScore 
    @feedProduct.save 
end 

如果由於某種原因,我通過在ID沒有找到,我發現我得到這個錯誤,多數民衆贊成罰款:

ActiveRecord::RecordNotFound: Couldn't find FeedProduct with id=999999 

我可以寫一些邏輯和檢查是否有得分,並且在我保存之前找到了一些東西,但它看起來不像Ruby的做事方式......我應該只是用邏輯來編寫來驗證,還是有一些Ruby/Ror的做法事情呢?

感謝

+0

試試嗎?http://api.rubyonrails.org/classes/Object.html#method-i-try – 2012-02-01 10:11:37

+0

這是一個FeedProduct的類方法嗎?你說可以舉例外嗎?然後使用find是好的。 – tokland 2012-02-01 10:41:04

回答

2

如果您想跟蹤錯誤消息並正確記錄,請按照@lucapette的答案。否則

def self.insert_feed_product_scores(id, low, high) 
    @feedProduct = FeedProduct.find(id) rescue return false 
    @feedProduct.avg_score = "#{low} - #{high}" 
    @feedProduct.save 
end 
+1

更好:'@feedProduct = FeedProduct.find_by_id(id)或返回false' – tokland 2012-02-01 10:41:37

+0

@tokland,使用'或'不會捕獲異常,因此代碼將在那裏破解。 – nkm 2012-02-01 13:41:03

+0

find_by_id不會引發異常。 – tokland 2012-02-01 15:09:06

2
def self.insert_feed_product_scores(id, low, high) 
    avgScore = low.to_s + " - " + high.to_s 
    begin 
    @feedProduct = FeedProduct.find(id) 
    @feedProduct.avg_score = avgScore 
    @feedProduct.save 
    rescue ActiveRecord::RecordNotFound 
    logger.info("Record not found: ", id) 
    end 
end 

這是做這件事的方式。但處理這種情況的不同方式是品味恕我直言的問題。

1

我平時做這樣的情況:

@feedProduct = FeedProduct.where(id: id).first 
if @feedProduct 
    @feedProduct.avg_score = avgScore 
    @feedProduct.save 
end 

那將節省安全產品。

0

這不是地道發送IDS到一個類的方法,我的方法添加到FeedProduct代替:

FeedProduct.find(feed_product_id).set_scores(1, 10) 

class FeedProduct 
    ... 
    def set_scores(low, high) 
    self.update_attribute(:avg_score, "#{low}-#{high}") 
    end 
    ... 
end 

是這個樣子使用

+0

哇,看起來很酷。真棒。 – 2012-02-01 20:35:16