循环列表中给删除功能加上Ajax特效

前几天一直想实现一个功能就是在循环显示的列表中,删除某一行数据时使用Ajax效果。今天似乎搞定了,唯一值得研究的一点就是对于element标记id的地方。下面给出这个实例的整个过程:
 
generate model product
 
数据迁移任务:
class CreateProducts < ActiveRecord::Migration 
  def self.up 
    create_table :products  do |t| 
      t.column :name,:string 
      t.column :content, :text 
    end 
  end 

  def self.down 
    drop_table :products 
  end 
end
建立一个controller,用来生成脚手架,可以添加product对象数据。
generate controller admin
在controller中添加scaffold :product
另外建立一个list_controller及其两个视图
generate controller list index delete
list_controller中的内容:
class ListController < ApplicationController 

  def index 
    @products=Product.find(:all, :order=>"name") 
     
  end 
   
  def delete 
    Product.find(params[:id]).destroy
     redirect_to :action=>"index" if request.xhr? 
  end 
end 
在index视图中,index.rhtml里添加代码:
<h1>List Products</h1> 
<table> 
<tr> 
  <th>name</th> 
  <th>content</th> 
</tr> 
<%@products.each do |product|%> 
  <tr id= <%="current_product#{product.id}"%>
      <td><%=h(product.name)%></td> 
      <td><%=h(product.content)%></td> 
      <td><%=link_to_remote "delete", :url=>{:action=>"delete", :id=>product}, :complete=>visual_effect(:fade,  "current_product#{product.id}")%></td> 
      </tr> 
    <%end%> 
 </table>
这样从admin/index里可以create products,在list里显示这些数据,也可以实现删除的Ajax效果,一切工作顺利。
这里还有个地方要注意下,    在delete这个action中要加上
redirect_to :action=>"index" if request.xhr?
如果不加这句,firebug会给出一个错误的提示,说你missing template "delete.rhtml", 虽然在支持Javascript的浏览器上不会发生错误,但是如果浏览器不支持Javascript,那么delete就不能正常运行了。




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/91650,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值