4

I am pretty new to Sinatra and am making a simple todo app that utilizes basic CRUD functionality.

In the backend I have working routes and have tested everything. I wanted to incorporate some front end functionality and decided to use jQuery to help with that. I have a current piece of code in jQuery that adds a css class to one of the todo items when that item is clicked. I wanted to include a button that says "Delete completed tasks" that would collect the tasks with the class of "completed" and than trigger the Sinatra route which would delete the tasks from the database. The current Sinatra route is:

delete "/hub/note/:id" do
   n = Note.get params[:id]
   n.destroy
   redirect '/hub'
end

How do I get jQuery and Sinatra to communicate the delete the items with the class of "completed". Any help would be incredibly useful.

Julian25
  • 675
  • 9
  • 19

2 Answers2

2

Utilizing the method_override trick/hack, you can get what you want by doing this:

jQuery.post("/hub/note/" + id, {_method: "delete"}, callback);

Anything leveraging Rack, including Sinatra and Ruby on Rails, should have this behavior.

Max
  • 4,882
  • 2
  • 29
  • 43
  • Thanks! Could I just grab the elements with class "completed" and send the above method on it? – Julian25 Apr 22 '12 at 19:06
  • Sure, that would work. The way I'd probably do this, personally, is by adding a data-id="1" or similar property to each tr (or li? whatever) that embodies the entire note and then do this: $(".completed").click(function(){ var id = $(this).closest("tr").data("id"); $.post("/hub/note/" + id, {_method: "delete"}, function(){ // whatever }); }); – Max Apr 22 '12 at 19:48
0

In your jQuery code.

$.post('/user/' + user.id, {_method: 'delete'}, function(result_data) {
  console.log('DELETE result', result_data);
}).error(function(){
  console.log("Error trying to DELETE");
});

In your Sinatra code

delete "/user/:id" do
  if request.xhr?
    content_type :json
    id = params[:id].to_i
    user = User.find_by_id(id)
    if !user
      status 404
      return {:success => false, :message => "Invalid ID supplied."}.to_json
    end
    user.destroy
    return {:success => true, :id => id, :message => "The User with ID #{id} was deleted."}.to_json
  end
  status 403
  return "<html><head><title>Error 403</title></head><body><h2>Expected an AJAX call.</h2></body></html>"
end

If your sinatra app is not a modular app then also include a set :method_override, true line with your other sets.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134