我是Ruby和Ror的新手所以任何指导都会很棒。我有一个功能:
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 :(得分: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 :(得分:2)
如果要跟踪错误消息并正确记录,请关注@luttette 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
答案 2 :(得分:1)
我通常在这种情况下这样做:
@feedProduct = FeedProduct.where(id: id).first
if @feedProduct
@feedProduct.avg_score = avgScore
@feedProduct.save
end
这将安全地保存产品。
答案 3 :(得分:0)
将 ids 发送到类方法并不是惯用的,我会向FeedProduct
添加一个方法:
class FeedProduct
...
def set_scores(low, high)
self.update_attribute(:avg_score, "#{low}-#{high}")
end
...
end
以这种方式使用:
FeedProduct.find(feed_product_id).set_scores(1, 10)