auto_complete

atuo_complete插件提供输入提示功能,我们通过一个example来示范,用户在输入日志的tag时,有自动输入提供。

  1. 创建测试工程:
$rails test_auto_complete
$cd test_auto_complete
  1. 生成blog和tag模型:
$script/generate scaffold blog title:string content:string
$script/generate model tag name:string blog_id:integer
  1. 映射一对多关系:
#app/models/blog.rb
has_many :tags
#app/models/tag.rb
belongs_to :blog
  1. 添加测试数据:
#db/migrate/001_create_blogs.rb
Blog.create(:title = test, :content = test)
#db/migrate/002_create_tags.rb
blog = blog.find(:first)
Tag.create(:name = ruby, :blog_id = blog)
Tag.create(:name = rails, :blog_id = blog)
Tag.create(:name = agile, :blog_id = blog)
Tag.create(:name = web, :blog_id = blog)
  1. 生成数据表:
$rake db:migrate
  1. 安装auto_complete插件:
$script/plugin install http://svn.rubyonrails.org/rails/plugins/auto_complete/
  1. 为controller添加auto_complete_for方法:
#app/controllers/blogs_controller.rb
auto_complete_for :tag, :name
  1. 在routes中添加映射关系:
#config/routes.rb
map.resources :blogs, :collection = { :auto_complete_for_tag_name = :get }
  1. 在view中添加需要提示功能的输入框:
#app/views/blogs/new.html.erb
Tags
<%= text_field_with_auto_complete :tag, :name, {}, {:method = :get} %>
  1. 确保页面已经包含prototype库:
#app/views/layout/blogs.html.erb
<%= javascript_include_tag :defaults %>
  1. 测试:
$script/server

在浏览器中输入http://localhost:3000/blogs/new 在Tags输入框中输入r,系统将提示ruby和rails

  1. 如果你想输入多个tag都有提示的话,比如用空格分开:
#app/views/blogs/new.html.erb
<%= text_field_with_auto_comlete :tag, :name, {}, {:method = :get, :token = ' '} %>

在Tags输入框中输入ruby on r,系统将提示ruby和rails

  1. 如果你想在光标进入输入框就提示的话,可以这样做:
#app/views/blogs/new.html.erb
<%= text_field_with_auto_complete :tag, :name, {:onfocus = tag_name_auto_completer.activate()}, {:method = :get, :token = ' '} %>

在Tags输入框为空时,点击该输入框,系统将提示agile, rails, ruby, web

Tips:

#Controller中可带参数有:conditions, :limit, :order
class BlogController  ApplicationController
  auto_complete_for :tag, :name, :limit = 15, :order = 'created_at DESC'
end
#View中可待参数有两种:
#一是tag_options,与text_field的options相同
#二是completion_options,与prototype库的Ajax.AutoCompleter的options相同
<%= text_field_with_auto_complete :tag, :name, {:size = 10}, {:tokens = ' '} %>

Posted in  rails plugins


blog comments powered by Disqus
Fork me on GitHub