views:

198

answers:

1

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 reports even if it fails (i guess REPLACE would be best, but afaik it's not available in ActiveRecord).

+3  A: 

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.

anshul