(GoRails)在導航欄增加一個global自動的搜尋功能。
Global Autocomplete Search
EasyAutocomplete jQuery外掛。
https://github.com/pawelczak/EasyAutocomplete
http://easyautocomplete.com/guide#sec-data-file
Every time you type into this box, it's going to fire an AJAX request, the server is going to do some searches, and combine those results into a JSON object that gets returned to the browser, and then your JavaScript library for the autocomplete will take those results, and then display them
1. 啟用一個Ajax request
2.server查詢,把查詢結果放入一個JSON物件,然後返回到瀏覽器。
3.JS庫EasyAutocomplete將得到這些結果並顯示它們。
本案例使用Categories feature. 一個很有用的工具。
第一步新增<script>
1.在<head>新增
<!-- Using jQuery with a CDN 加上jquery檔案 --> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
2.把檔案放入assets/javascripts和stylesheets
官網下載,http://easyautocomplete.com/download
- 把easy-autocomplete.css和easy-autocomplete.themes.css放入Rails app的 app/asset/stylesheets資料夾。
- 把jquery.easy-autocomplete.js放入javascript資料夾。
- 在application.js中加上//= require jquery.easy-autocomplete
- 在application.scss中加上*= require easy-autocomplete和*= easy-autocomplete.thems
3. 在瀏覽器的console上試試:
第二步: 新增路徑。
get :search, controller: :main //或者 get 'search', to: "main#search"
輸入rails routes可檢視
建立一個main_controller.rb
class MainController < ApplicationController def index end def search render json: {movies: [], directors: []} end end
在瀏覽器輸入localhost:3000/search
渲染JSON:
第三步
新增gem 'ransack'
class MainController < ApplicationController ... def search @movies = Movie.ransack(params[:q]).result(distinct: true) @directors = Directors.ransack(params[:q]).result(distinct: true)
//可以限制條數.limit(5) end end
新建views/main/search.json.jbuilder
json.movies do json.array!(@movies) do |movie| json.name movie.name json.url movie_path(movie) end end json.directors do json.array!(@directors) do |director| json.name director.name json.url director_path(director) end end
新增一個回撥before_action: force_json, only: :search
這樣瀏覽器輸入的url字尾會被轉化為.json
class MainController < ApplicationController private def force_json request.format = :json end end
class MainController < ApplicationController ... def search @movies = Movie.ransack(name_cont: params[:q]).result(distinct: true) @directors = Directors.ransack(name_cont: params[:q]).result(distinct: true).limit(5) //name_cont限制查詢的key是name end end