`
sunfengcheng
  • 浏览: 180695 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

自动完成文本字段

阅读更多
如果你输入文本字段的时候自动填充短语 或者单词,那么这里将告诉你很容易i的实现。

首先定义一个迁移数据库,
db/migrate/001_create_musicians.rb:

class CreateMusicians < ActiveRecord::Migration
  def self.up
    create_table :musicians do |t|
      t.column :name, :string
    end

    Musician.create :name => 'Paul Motion'
    Musician.create :name => 'Ed Blackwell'
    Musician.create :name => 'Brian Blade'
    Musician.create :name => 'Big Sid Catlett'
    Musician.create :name => 'Kenny Clarke'
    Musician.create :name => 'Jack DeJohnette'
    Musician.create :name => 'Baby Dodds'
    Musician.create :name => 'Billy Higgins'
    Musician.create :name => 'Elvin Jones'
    Musician.create :name => 'George Marsh'
    Musician.create :name => 'Tony Williams'
  end

  def self.down
    drop_table :musicians
  end
end




接着 ,将这个表和一个 Active Record  模型联系起来。

app/models/musician.rb:

class Musician < ActiveRecord::Base
end





下一步  使用布局中的javascript_include_tag   来包含 JavaScript 库

/views/layouts/musicians.rhtml:

<html>
<head>
  <title>Musicians: <%= controller.action_name %></title>
  <%= javascript_include_tag :defaults %>
</head>
<body>

<%= yield %>

</body>
</html>


控制器包含一个对auto_complete_for 的调用, 这个方法的参数是模型对象 以及用作自己自动完成的对象的字段。
app/controllers/musicians_controller.rb:

class MusiciansController < ApplicationController

  auto_complete_for :musician, :name

  def index
  end

  def add
    # assemble a band...
  end
end


通常需要自动完成的字段会作为一个表单 的一部分,在这里我们就创建一个简单的表单来输入音乐家。
app/views/musicians/index.rhtml:

<h1>Musician Selection</h1>

<% form_tag :action => :add do %> 
  <%= text_field_with_auto_complete :musician, :name %>
  <%= submit_tag 'Add' %>
<% end %>
3
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics