title: Rails conditional redirect after delete
body: <p>I'm trying to redirect after a delete depending on where the user came from.</p>
  
  <p>This is the current code in the event controller:</p>
  
  <pre><code>def destroy
    @event = Event.find(params[:id])
    @event.destroy
  
    respond_to do |format|
      format.html { redirect_to events_url }
      format.json { head :no_content }
    end
  end
  </code></pre>
  
  <p>I changed it to this (thanks MrYoshiji):</p>
  
  <pre><code>format.html { redirect_to :back }
  </code></pre>
  
  <p>That works if the user was deleting from all pages except the Event show page.  Because you then get an error trying to show a record you just deleted.</p>
  
  <p>So, I'm trying to use a params to tell the destroy code where to redirect to.</p>
  
  <p>I'm trying this:</p>
  
  <pre><code>def destroy
    @event = Event.find(params[:id])
    @event.destroy
    @return_url
  
    respond_to do |format|
      format.html { redirect_to @return_url }
      format.json { head :no_content }
    end
  end
  </code></pre>
  
  <p>But, I don't know how to pass the @return_url as a param in the link_to on a  show page. </p>
  
  <pre><code>    &lt;%= link_to 'Delete', @event, params(@return_url =&gt; "some url"), confirm: 'Are you sure?', method: :delete, :class =&gt; 'btn btn-danger' %&gt;
  </code></pre>
  
  <p>How would I pass the url as a param?</p>
  
  <p>Thanks!!</p>
  
  <p>UPDATE1</p>
  
  <p>I changed the Event controller to this:</p>
  
  <pre><code> def destroy
     @expense = Expense.find(params[:id])
     redirect_url = (request.referer.include?("#{@event.id}/show") ? events_url : :back)
     @expense.destroy
  
     respond_to do |format|
       format.html { redirect_to redirect_url }
       format.json { head :ok }
     end
   end
  </code></pre>
  
  <p>This redirects back to the correct page the "Delete Event" button is on - except when I click that button on the show page for the Event.</p>
  
  <p>The redirect wants to show the deleted record.</p>
  
  <p>UDPATE2</p>
  
  <p>OK this worked for my app:</p>
  
  <pre><code>    redirect_url = (request.referer.include?("/events/#{@event.id}") ? events_url : :back)
  </code></pre>
  
  <p>THANKS FOR ALL THE HELP !!</p>