Apr 12 2008
go.6.cn是功能一个把长网址转为短网址进行跳转。其原理可以说是当用户插入数据时,查询数据库是否存在该网址,有则插入,没则新建并返回给该网址。
用Rails来实现这个功能,可以用find_or_create_by_来实现,代码如下。
def index
@ad = Ad.new
end
def save
ad = Ad.find_or_create_by_tu(params[:ad]['tu'])
flash[:notice] = ad.id
redirect_to(:action => ‘index’)
end
def page
@ad = Ad.find(params[:id])
if @ad.tu =~ /^http:\/\//
redirect_to(@ad.tu)
else
redirect_to(”http://#{@ad.tu}”)
end
end
end
view文件
<% if flash[:notice] -%>
127.0.0.1:3000/page/<%= flash[:notice] %>
<% end -%>
#把[和]去掉
Ad表结构
def self.up
create_table :ads do |t|
t.column :id, :int
t.column :tu, :string
end
add_index :ads, :tu, :unique =>true
#添加索引
end
很简陋的,仅供参考
