diff app/controllers/pastes_controller.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 26545fe719ca
children e84276bf344a
line wrap: on
line diff
--- a/app/controllers/pastes_controller.rb	Sat Jun 06 22:01:08 2015 +0900
+++ b/app/controllers/pastes_controller.rb	Sat Jun 06 22:12:56 2015 +0900
@@ -28,28 +28,23 @@
   # POST /pastes.json
   # POST /pastes.txt
   def create
-    @paste = Paste.new paste_params.merge(:ip => request.remote_ip)
+    created, @paste, @fresh = Paste.graceful_create paste_params.merge(:ip => request.remote_ip)
 
-    begin
-      respond_to do |format|
-        if @paste.save
-          @fresh = true
+    respond_to do |format|
+      if created
+        if @fresh
           format.html { redirect_to @paste, :notice => "Paste was successfully created." }
           format.json { render :json => @paste, :status => :created, :location => @paste }
         else
-          flash.now[:alert] = @paste.errors.full_messages.to_sentence
-          format.html { render :action => "new" }
-          format.json { render :json => @paste.errors, :status => :unprocessable_entity }
+          format.html { redirect_to paste_path(@paste) }
+          format.json { render :json => @paste }
         end
-        format.txt
+      else
+        flash.now[:alert] = @paste.errors.full_messages.to_sentence
+        format.html { render :action => "new" }
+        format.json { render :json => @paste.errors, :status => :unprocessable_entity }
       end
-    rescue ActiveRecord::RecordNotUnique
-      @paste = Paste.where(:ip => @paste.ip, :paste_hash => @paste.paste_hash).first
-      respond_to do |format|
-        format.html { redirect_to paste_path(@paste) }
-        format.json { render :json => @paste }
-        format.txt
-      end
+      format.txt
     end
   end