2012-02-01 7 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が見つからなかった何らかの理由場合は、私はこのエラーを取得するに気づくには、罰金のthats:

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

私はいくつかのロジックを記述でき、もしスコアがあり、私が保存する前に見つかったものがあるかどうかをチェックしてください。しかし、Rubyのやり方のようには見えません...私はただ検証するロジックを書くべきでしょうか、Ruby/Rorのやり方です物事?

おかげ

+0

try?http://api.rubyonrails.org/classes/Object.html#method-i-try –

+0

これはFeedProductのクラスメソッドですか?例外を発生させてもいいですか? findを使ってOKです。 – tokland

答えて

2

エラーメッセージを追跡して正しくログする場合は、@lucapette answerに従ってください。エルス

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

better: '@feedProduct = FeedProduct.find_by_id(id)またはfalseを返す' – tokland

+0

@tokland、 'or'を使用して例外をキャッチしないため、コードがそこに壊れます。 – nkm

+0

find_by_idは例外を発生させません。 – tokland

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 

は、それはそれを行うための方法です。しかし、このような状況を扱うさまざまな方法は、味の問題です。IMHO。

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

Whoa cool looking。驚くばかり。 –

関連する問題