I am currently working on developing a task management app using Rails. Each to-do list in the app contains multiple tasks, and my issue lies in deleting a completed task with Ajax without having to manually refresh the page for it to vanish. As I am still new to Rails and Javascript, any advice or suggestions would be highly appreciated.
Below is the code snippet from my Items destroy Javascript file:
<% if @item.destroyed? %>
$('#item-' +<%= @item.id %>).hide();
<% else %>
$('#item-' +<%= @item.id %>).prepend("<div class='alert alert-danger'><%= flash[:error] %></div>");
<% end %>
The following code is from the Lists#show view which calls the item partial:
%h1= @title
.row
.col-md-6
= render 'items/item', locals: {items: @items}
.row
.col-md-6
= render 'items/form', locals: {list: @list, item: @item}
= link_to "Edit", edit_list_path(@list), class: 'btn btn-success'
= link_to "Delete List", @list, method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this to-do list?' }
- if @lists.nil?
= link_to "New To-do List", new_list_path, class: 'btn btn-success'
The Item partial section is as follows:
- @items.each do |item|
= item.name
= link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
%br/
This is the implementation in the Items Controller:
class ItemsController < ApplicationController
respond_to :html, :js
def create
@list = List.find(params[:list_id])
@item = @list.items.new(item_params)
@item.user_id = current_user.id
if @item.save
redirect_to @list, notice: 'Your new To-Do Item was saved!'
else
redirect_to @list, notice: 'You forgot to enter a To-Do item. Please try again.'
end
end
def destroy
@list = current_user.lists.find(params[:list_id])
@item = @list.items.find(params[:id])
@title = @list.title
if @item.destroy
flash[:notice] = "\"#{@item.name}\" was deleted successfully."
else
flash[:error] = "There was an error deleting the list."
end
respond_with(@item) do |format|
format.html {render [@list]}
end
end
def item_params
params.require(:item).permit(:name)
end
end