开发者

rails/mysql - how do i silence out ActiveRecord::StatementInvalid error?

i am writing a code to handle read/unread messages, with a simple user_id/message_id mysql table to handle read/unread status.

when the user views the message, i execute

Reading.create(:user_id => uid, :message_id => mid)

there is unique index on user_id/message_id fields combination, so when the entry in Readings already exists, i get ActiveRecord::StatementInvalid error about duplicate entry.

now i could add

unless Reading.exists?(:user_id => uid, :message_id => mid)
 Reading.create(:user_id => uid, :message_id => mid)
end

but i imagine this adds one more SELECT query before INSERT

i'd prefer to have just one INSERT, and no error repo开发者_运维知识库rts even if it fails (i guess REPLACE would be best, but afaik it's not available in ActiveRecord).


Rescue it

begin
  Reading.create(:user_id => uid, :message_id => mid)
rescue ActiveRecord::StatementInvalid => error
  raise error unless error.to_s =~ /Mysql::Error: Duplicate/
end

This is a bit ugly but will work. Consider tightening up the regex in unless to match out exactly the kind of error you are getting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜