i am writing a code to handle read/unread messages, with a simple user_id/message_id mysql table to handle read/unread status.
我正在编写一个代码来处理读/未读消息,使用一个简单的user_id/message_id mysql表来处理读/未读状态。
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.
user_id/message_id字段组合上有唯一的索引,所以当读数中的条目已经存在时,我将获得ActiveRecord: StatementInvalid error关于重复条目。
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
但是我想这在插入之前会增加一个SELECT查询
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).
我希望只有一个插入,即使失败也不要有错误报告(我认为替换是最好的,但是在ActiveRecord中不可用)。
1 个解决方案
#1
5
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.
这有点难看,但可以用。考虑收紧regex,除非与您所得到的错误完全匹配。
#1
5
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.
这有点难看,但可以用。考虑收紧regex,除非与您所得到的错误完全匹配。