插件介绍:auto-completion

由于rails2已经把自动完成(auto-completion)移出去了,2.0后的自动完成可以用下面的插件来完成。

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

1. 创建测试工程:
$rails test_auto_complete
$cd test_auto_complete

2. 生成blog和tag模型:
$script/generate scaffold blog title:string content:string
$script/generate model tag name:string blog_id:integer

3. 映射一对多关系:
#app/models/blog.rb
has_many :tags

#app/models/tag.rb
belongs_to :blog


4. 添加测试数据:
#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)


5. 生成数据表:
$rake db:migrate


6. 安装auto_complete插件:
$script/plugin install http://svn.rubyonrails.org/rails/plugins/auto_complete


7. 为controller添加auto_complete_for方法:
#app/controllers/blogs_controller.rb
auto_complete_for :tag, :name

8. 在routes中添加映射关系:
#config/routes.rb
map.resources :blogs, :collection => { :auto_complete_for_tag_name => :get }


9. 在view中添加需要提示功能的输入框:
#app/views/blogs/new.html.erb

Tags
<%= text_field_with_auto_complete :tag, :name, {}, {:method => :get} %>



10. 确保页面已经包含prototype库:
#app/views/layout/blogs.html.erb
<%= rubyscript_include_tag :defaults %>


11. 测试:
script/server
在浏览器中输入 http://localhost:3000/blogs/new
在Tags输入框中输入r,系统将提示ruby和rails
插件介绍:auto-completion

12. 如果你想输入多个tag都有提示的话,比如用空格分开:
#app/views/blogs/new.html.erb
<%= text_field_with_auto_comlete :tag, :name, {}, {:method => :get, :token => ' '} %>
在Tags输入框中输入ruby on r,系统将提示ruby和rails
插件介绍:auto-completion
13. 如果你想在光标进入输入框就提示的话,可以这样做:
#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
插件介绍:auto-completion

    以上测试环境是:Ruby 1.8.6 + Rails 2.0.2,点击 这里下载源代码

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 => ' '} %>


这里还有一版不错的英文的 用法介绍

示例一点:
def auto_complete_for_doctor_organization
  re = Regexp.new("^#{params[:doctor][:organization]}", "i")
  find_options = { :order => "name ASC" }
  @organizations = Organization.find(:all, find_options).collect(&:name).select { |org| org.match re }
        
  render :inline => "<%= content_tag(:ul, @organizations.map { |org| content_tag(:li, h(org)) }) %>"
end

map.auto_complete ':controller/:action', 
                  :requirements => { :action => /auto_complete_for_\S+/ },
                  :conditions => { :method => :get }

你可能感兴趣的:(SVN,prototype,Blog,Ruby,Rails)