diff app/models/paste.rb @ 373:6e3e1e7b0212

Handle unique error in model instead of controller.
author nanaya <me@myconan.net>
date Sat, 06 Jun 2015 22:12:56 +0900
parents 96631607785f
children 02903dc8214d
line wrap: on
line diff
--- a/app/models/paste.rb	Sat Jun 06 22:01:08 2015 +0900
+++ b/app/models/paste.rb	Sat Jun 06 22:12:56 2015 +0900
@@ -22,6 +22,21 @@
     end
   end
 
+  def self.graceful_create(params)
+    paste = self.new(params)
+    fresh = true
+    created = true
+
+    begin
+      created = paste.save
+    rescue ActiveRecord::RecordNotUnique
+      paste = self.find_by(:ip => paste.ip, :paste_hash => paste.paste_hash)
+      fresh = false
+    end
+
+    return [created, paste, fresh]
+  end
+
   def paste_gzip=(paste)
     self.paste = ActiveSupport::Gzip.decompress paste
   end