每天一剂Rails良药之Live Search

这次我们看看Rails里text_field的auto_complete,即Live Search。

1,添加Recipe的Migration
[code]
class AddRecipes < ActiveRecord::Migration
def self.up
create_table :recipes do |t|
t.column :name, :string
end
end

def self.down
drop_table :recipes
end
end
[/code]

2,添加SearchController
[code]
class SearchController < ApplicationController
auto_complete_for :recipe, :name
end
[/code]
这里的auto_complete_for :recipe, :name会告诉Rails自动生成一个auto_complete_for_recipe_name()方法,它将搜索匹配输入的文本的对象并渲染结果。

3,添加search.rhtml
[code]
<html>
<head>
<%= javascript_include_tag :defaults %>
</head>
<body>
<h1>Search Recipes</h1>
Name:<%= text_field_with_auto_complete :recipe, :name %>
</body>
</html>
[/code]
text_field_with_auto_complete这个Helper方法会在页面生成一些HTML和JavaScript,从而使得recipe的name域自动搜索和补全。
向数据库加几条数据并访问[url]http://localhost:3000/search/search[/url]看看效果吧!
如此简洁的几行代码就为我们添加Live Search功能,何乐而不为呢?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值