rails2.0之前類庫里已經封裝了自動完成功能,rails2.0以后被分離了出來,作為插件使用.
插件作用:能夠實現自動完成 和 自動提示 功能
我的環境:ruby1.8.6 + rails 2.1.0
效果預覽:
使用案例一:(簡單的使用)
1,下載插件
(1),直接到網站上下載 http://github.com/rails/auto_complete/tree/master
(2),在項目中下載,進入項目目錄 輸入 ruby script/plugin auto_complete 自動安裝插件到項目下,默認是從http://dev.rubyonrails.com/svn/rails/plugins 站點下載的,所以完整的下載路徑是
ruby script/plugin install http://dev.rubyonrails.com/svn/rails/plugins/auto_complete/
這里可以利用 ruby script/plugin list 查看有哪些插件可以下載
2,直接按照插件的 readme 操作(請查看插件的readme)
# Controller
class BlogController < ApplicationController
auto_complete_for :post, :title #post對應著model(即表),title對應著表的一個字段
end
# View
<%= text_field_with_auto_complete :post, title %>
3,在layouts下 新建一個blog.rhtml,把下面代碼包括進來
<%= javascript_include_tag :defaults %>
4,如果到這里你還是沒有成功的話,建議在controller中添加
skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_post_title] #我做的時候就是加了這個skip filter的,不然運行不穩定
5,ok....success!
案列二:(加一些約束條件)
其它步驟基本不變,可以在model中指定顯示的條數和字段 什么的
eg:
Model中:
class Fruit < ActiveRecord::Base
# 定義一個查詢方法,
def self.find_fruit_by_part(part)
# 查詢出所有name匹配part的水果實體,最多顯示5條
Fruit.find(:all, :conditions => ["name LIKE ?", "%" + part + "%" ],:limit => 5);
end
end
Controller中:
class FruitController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_user_fruit]
def index
end
def auto_complete_for_user_fruit
begin
fruit = params[:user][:fruit]
rescue
# 如果不能正常取得請求參數,給一個默認參數
fruit = "an"
end
@results = Fruit.find_fruit_by_part(fruit);
render :inline => "<%= auto_complete_result @results, 'name' %>"
end
end
view中:
<h3>測試自動完成功能</h3>
<p>
<%= text_field_with_auto_complete :fruit, :name %>
</p>
案列三:添加css樣式
css:
.useraddress{
font-size:12px;
color:#628B24
}
controller:
class MessageController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_message_to]
def auto_complete_for_message_to()
user_name = params[:message][:to]
@customers = Customer.find(:all , :conditions=>"name like '%"+user_name.downcase+"%'")
render :partial => 'username'
end
end
view:
new.rhtml
auto_complete 自動提示:<br/><br>
<%= text_field_with_auto_complete 'message', 'to',{}, :skip_style => false %>
_username.rhtml
<ul class="allusers">
<% for customer in @customers do %>
<li class="thisuser">
<div class="username">
<%=h customer.name %>
</div>
<div class="useradd">
<span class="useraddress">
<%=h customer.address %>
</span>
</div>
</li>
<% end %>
</ul>
案列源碼下載:
http://www.namipan.com/d/080744d037c133836019281306a7d90e1e546d8a3d970100
ref:
http://share-facts.blogspot.com/2009/02/autocompleter-example-in-ruby-on-rails.html
http://jbf034.javaeye.com/blog/215429
續:
如果想修改默認的auto_complete的css樣式,到auto_complete_macros_helper.rb文件下找到auto_complete_stylesheet方法修改即可,我修改后的css

posted on 2009-03-31 16:21
fl1429 閱讀(1125)
評論(0) 編輯 收藏 所屬分類:
Rails