我试图在我的应用程序中实现一点Ajax似乎工作正常但是在执行操作后它没有更新页面。
我在我的Destroy方法中添加了Ajax
def destroy
@item = Item.find(params[:id])
@item.user = current_user
if @item.destroy
flash[:notice] = "Item Completed"
else
flash[:alert] = "Item was unable to be marked completed "
end
respond_to do |format|
format.html
format.js
end
end
我已使用remote: true
更新了我的_item.html.erb和_form.html.erb部分
<%= content_tag :div, class: 'media', id: "item-#{item.id}" do %>
<div class="media">
<div class="media-body">
<small>
<%= item.name.titleize %>
| submitted <%= time_ago_in_words(item.created_at) %>
<% if current_user == @user %>
<%= link_to "Completed ", [@user, item], method: :delete,remote: true, class: 'glyphicon glyphicon-ok' %><br>
<% end %>
</small>
</div>
</div>
<% end %>
_from.html.erb
<%= form_for [@user, item ], remote: true do |f|%>
<div class="form-group">
<%= f.label :name, class: 'sr-only' %>
<%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
</div>
<%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %>
<% end %>
User#show view <div class='new_item'>
<%= render :partial => 'items/form', :locals =>{:item => Item.new} %>
</div>
<% end %>
<div class='js-items'>
<% @user.items.order('created_at DESC').each do |item| %>
<%= render :partial => 'items/item' , :locals => {:item => item } %>
</div>
destroy.js.erb
$('#item-<%= @item.id %>').hide();
就像我之前说的那样,当我点击删除按钮时,项目被删除但我需要刷新页面才能看到更新的页面。任何想法,我可能做错了,任何推向正确的方向将不胜感激!
答案 0 :(得分:0)
尝试在方法本身中渲染java脚本并检查
def destroy
@item = Item.find(params[:id])
@item.user = current_user
if @item.destroy
flash[:notice] = "Item Completed"
else
flash[:alert] = "Item was unable to be marked completed "
end
respond_to do |format|
format.html
format.js { render
$('#item-<%= @item.id %>').hide();
}
end
end