我正在进行铁路分配,需要我创建一个销毁待办事项列表中的项目的复选框。我目前正在获取一个未定义的局部变量或方法`item,'但我不认为这是我的项目#destroy action的整体问题。我应该把项目变成@item吗?
物品管制员:
class ItemsController < ApplicationController
def new
@user = User.find(params[:user_id])
@item = Item.new
end
def create
@user = User.find(params[:user_id])
@item = Item.new(params.require(:item).permit(:name))
@item.user_id = @user.id
if @item.save
flash[:notice] = "Item was saved."
redirect_to [@user, @item]
else
flash[:error] = "There was an error saving the item. Please try again."
render :new
end
end
def show
@user = User.find(params[:user_id])
@item = Item.find(params[:id])
end
def destroy
@user = User.find(params[:user_id])
@item = Item.find(params[:id])
if @item.destroy
flash[:notice] = "Item was removed."
else
flash[:error] = "Item couldn't be deleted. Try again."
end
respond_to do |format|
format.html
format.js
end
end
Destroy.js.erb
$('#item-' +<%= @item.id %>).hide();
用户显示:
<br>
<div class="container">
<div class="row">
<div class="col-md-11">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-12 lead">User profile<hr></div>
</div>
<div class="row">
<div class="col-md-4 text-center">
<img class="img-circle avatar avatar-original" style="-webkit-user-select:none;
display:block; margin:auto;" src="http://robohash.org/sitsequiquia.png?size=120x120">
</div>
<div class="col-md-8">
<div class="row">
<div class="col-md-12">
<h1 class="only-bottom-margin"><%= @user.email%></h1>
</div>
</div>
<div class="row">
<div class="col-md-6">
<span class="text-muted">Name:</span> <%= @user.name%><br>
<span class="text-muted">Id:</span> <%= @user.id %><br>
</div>
<div class="col-md-10">
<h3>User's To-Do List</h3>
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
<%= render partial: 'items/item'%>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
当你的观点被调用时(即destroy.js.erb
),@item
将被销毁。只需添加一个缓存item
id的变量:
def destroy
@user = User.find(params[:user_id])
@item = Item.find(params[:id])
@item_id = @item.id
if @item.destroy
flash[:notice] = "Item was removed."
else
flash[:error] = "Item couldn't be deleted. Try again."
end
respond_to do |format|
format.html
format.js
end
然后在destroy.js.erb
:
$('#item-' +<%= @item_id %>).hide();
答案 1 :(得分:0)
我相信您的视图中会引入错误:
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
我没有看到“物品”的制定者。任何地方,这将阻止link_to方法推断其类型和路线。
似乎缺少的是通过用户的项目循环,有些内容......
<h3>User's To-Do List</h3>
<% @user.items.each do |item| %>
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
<%= render partial: 'items/item'%>
<% end %>
请注意,此解决方案假设用户和项之间的关系,特别是User.rb模型中的has_many:项。