Mercurial > zeropaste
changeset 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 | 117accbc72c3 |
children | 92c62966191b |
files | app/controllers/pastes_controller.rb app/models/paste.rb |
diffstat | 2 files changed, 26 insertions(+), 16 deletions(-) [+] |
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
--- 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