如何使用ajax从html表中删除条目

时间:2014-04-07 06:53:04

标签: jquery ruby-on-rails ajax

我在我的视图中搜索从现有html表中删除条目的解决方案。

我现在实施了以下部分:

控制器:

def destroy_user_role
 TopicPremission.find(params[:role_id]).destroy if request.post?
 respond_to do |format|
   format.html 
   format.js
 end
end 

视图(_save_role.html.erb):

<table class="list user_roles">
 <tr>
  <th><%= User %></th>
  <th><%= Role %></th>
  <th style="width:15%"></th>  
 </tr>
 <% @actual_roles.each do |role| %>
  <tr>
  <td><%= value = @users.detect{|u| u.id == role.user_id} 
       value.firstname + " " + value.lastname %></td> 

  <% if role.level == 1 %>
    <td><%= "READ" %></td>
  <% elsif role.level == 2 %>
    <td><%= "READ/WRITE" %></td>
  <% end %>   

  <td><%= link_to "Destroy", {controller: "topics" , action: "destroy_user_role", :role_id => role.id , :id => params[:id]},  :remote => true,:method => :post ,  class: "icon icon-del" %></td>    
 <% end %>
</table>

.js.erb:

$('table.user_roles').html('<%= escape_javascript(render :partial => 'save_role') %>')

使用此代码我总是得到500错误,但我无法找到失败。希望有人可以帮助我!

1 个答案:

答案 0 :(得分:1)

这样做:

#_save_role.html.erb
<% @actual_roles.each do |role| %>
  <tr id="<%= role.id %>">
     <td>
        <%= value = @users.detect{|u| u.id == role.user_id} %>
        <%= value.firstname + " " + value.lastname %>
     </td> 
     <td>
        <% permission = (role.level == "2") ? "/WRITE" : "" %>
        <%= "READ#{permission}" %>
     </td>
     <td>
      <%= link_to "Destroy", {controller: "topics" , action: "destroy_user_role", :role_id => role.id , :id => params[:id]},  :remote => true,:method => :post ,  class: "icon icon-del" %>
     </td> 
  </tr>   
<% end %>


#app/controllers/your_controller.rb
respond_to :html, :js

def destroy_user_role
 @role = TopicPremission.find(params[:role_id])
 @id = @role.id

 @role.destroy if request.post?
 respond_with @id #-> Could send @role.id, but it may be deleted
end 

#app/views/controller/destroy_user_role.js.erb
$('<%=j "##{@id}" %>').fadeOut(150, function(){
     $(this).remove();
});