我正在尝试将AJAX应用于我的应用程序而不是删除item
,而是删除该项目所属的list
。我的lists#show
页面上显示项目的代码如下。在我将remote: :true
添加到内容之前,一切正常:
<% @items.each do |item| %>
<p><%= link_to "", list_item_path(@list, item), method: :delete, remote: :true, class: 'glyphicon glyphicon-ok', style: "margin-right: 10px" %> <<<<AJAX MODIFICATION HERE
<%= item.name %>
<% if item.delegated_to != "" && item.user_id == current_user.id %>
<small>(Delegated to <%= item.delegated_to %>)</small>
<% elsif item.delegated_to != "" && item.user_id != current_user.id %>
<small>(Delegated by <%= item.user_id %>)</small>
<% end %></p>
<% end %>
以下是我添加的items/destroy.js.erb
文件:
$('#item-<%= @item.id %>').hide();
任何人都可以帮我弄清楚为什么删除列表而不是项目?我对Javascript不太熟悉。
附加信息:
user GET /users/:id(.:format) users#show
home_index GET /home/index(.:format) home#index
root GET / home#index
list_items GET /lists/:list_id/items(.:format) items#index
POST /lists/:list_id/items(.:format) items#create
new_list_item GET /lists/:list_id/items/new(.:format) items#new
edit_list_item GET /lists/:list_id/items/:id/edit(.:format) items#edit
list_item GET /lists/:list_id/items/:id(.:format) items#show
PATCH /lists/:list_id/items/:id(.:format) items#update
PUT /lists/:list_id/items/:id(.:format) items#update
DELETE /lists/:list_id/items/:id(.:format) items#destroy
lists GET /lists(.:format) lists#index
POST /lists(.:format) lists#create
new_list GET /lists/new(.:format) lists#new
edit_list GET /lists/:id/edit(.:format) lists#edit
list GET /lists/:id(.:format) lists#show
PATCH /lists/:id(.:format) lists#update
PUT /lists/:id(.:format) lists#update
DELETE /lists/:id(.:format) lists#destroy
以下是items#controller
删除部分:
def destroy
@list = List.friendly.find(params[:list_id])
@item = Item.find(params[:id])
if @item.destroy
flash[:notice] = "Item was deleted successfully."
else
flash[:alert] = "Item couldn't be deleted. Try again."
end
respond_to do |format|
format.html
format.js
end
end
使用console.log("hello")
测试的控制台日志:
答案 0 :(得分:0)
我得到了SO的帮助,以及最终的工作:
<% @items.each do |item| %>
<%= div_for(item) do %>
<p><%= link_to "", list_item_path(@list, item), method: :delete, remote: true, class: 'glyphicon glyphicon-ok', style: "margin-right: 10px" %>
<%= item.name %>
<% if item.delegated_to != "" && item.user_id == current_user.id %>
<small>(Delegated to <%= item.delegated_to %>)</small>
<% elsif item.delegated_to != "" && item.user_id != current_user.id %>
<small>(Delegated by <%= item.user_id %>)</small>
<% end %></p>
<% end %>
<% end %>
和
$('#item_<%= @item.id %>').remove();