Rails / mysql - how to disable ActiveRecord :: StatementInvalid error?

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

when the user views the message, I execute

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

there is a unique index in the user_id / message_id combination of fields, so when a record in Readings already exists, I get an ActiveRecord :: StatementInvalid error about a duplicate record.

now i could add

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

but I think this adds another SELECT query to INSERT

I would prefer to have only one INSERT and no error reports even if it does not work (I think REPLACE will be better, but afaik it is not available in ActiveRecord).

+3
1

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

, . , , , .

+5

Source: https://habr.com/ru/post/1736457/


All Articles