Sinatra view doesn't refresh after some delete requests

In my Sinatra view, I have a table which will display all records from my database. When I click to delete a record I will call the jquery ajax to send the delete request. My route will then handle the request, delete the record in the database and redirect the app to its homepage.

The problem is that the view doesn't refresh after delete and still show some old data. When I close the browser and open it again the data still exists in the view even though the delete request has returned 200 code status.

# application_controller.rb

require 'sinatra'
require 'sinatra/reloader'
require './application_helper' if development?

enable :logging

helpers ApplicationHelper

...

delete '/delete/:record_id' do
  id = get_record_id
  delete_record id
  redirect '/'
end

get '/' do
  @links = get_all @user_ip
  erb :index, { :layout => :layout }
end

And here is the simplified code of the view:

# index.erb

<% if !@links.empty? %>
<div class="table-responsive" style="margin-top: 30px">
  <table class="table table-striped table-hover" style="width: 600px">
    <thead>
      <tr>
        <th>Original URL</th>
        <th>Short URL</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody>
      <% @links.each do |record| %>
        <tr>
          <td><a href=<%= record.long_url %>><%= record.long_url %></td>
          <td><a href=<%= record.id %>><%= record.short_url %></td>
          <td>
            <button class="btn btn-default" onClick="deleteRecord(<%= record.id %>)">
              <span class="glyphicon glyphicon-trash" style="color: red"></span>
            </button>
          </td>
        </tr>
      <% end %>
    </tbody>
  </table>
</div>
<% end %>

Here is the full source code on GitHub: https://github.com/huyvohcmc/bitly

1 answer

  • answered 2018-01-12 09:58 Huy Vo

    Well after some hours googling I can finally make it to work by changing both the controller and the view a little bit:

    # application_controller.rb
    
    delete '/delete/:record_id' do
      id = get_record_id
      delete_record id
      redirect '/'
    end
    
    # index.erb
    
    var deleteRecord = function (id) {
        $.ajax({
          url: '/delete/' + id,
          type: 'DELETE',
          success: function(data) {
            location.reload();
          }
        })
      }
    

    Basically, I have to reload the page manually after deleting a record. I don't know yet if Sinatra support this functionality but for now this method works like a charm :)