匹配搜索建议的API中的字符串

时间:2016-01-08 16:40:25

标签: javascript ruby-on-rails ruby json api

我目前正在努力重新创建此功能:Desired Functionality

我的代码的当前状态如下: 应用程序/资产/ JavaScript的/ schools.js

$(document).ready(function() {
   console.log( 'Jquery is working' );

$('#user_zip').keyup(function( event ) {
console.log ( 'Keyup is working' );
var zip_user_entry = $(event.target).val()

// ajax request
console.log(zip_user_entry);
$.get('/schools_in_zip_code', {zip_code: zip_user_entry})
});
});

我的学校控制器app / controllers / schools_controller.rb

class SchoolsController < ApplicationController
def index
  @schools = School.all.limit(15)
    respond_to do |format|
       format.json { render json: @schools }
    end
 end

 def in_zip_code
   @schools = School.all
   @school_suggestions = School.where(zip_code: LIKE params[:zip_code])
      respond_to do |format|
          format.json { render json: @school_suggestions }
      end
 end

 end

以下是我的观点:file - app / views / schools / in_zip_code.html.erb

Actual view partial code for building a select box with all the school options goes here. You will have access to the @schools variable. (still working on this)

应用程序/视图/学校/ in_zip_code.js

$('#selector-for-schools-in-this-zip-code').html('<%= escape_javascript(render(partial: "in_zip_code"))%>');

最后但并非最不重要的是这是我的config / routes.rb

get 'schools_in_zip_code' => 'schools#in_zip_code'
resources :schools, :defaults => { :format => 'json' }

我最挣扎的事情是,我没有从我的学校管理员那里得到我的学校教育的json。我的学校指数行动给了我json而不是school_suggestion。每当我得到KeyUp事件被触发时,这就是我得到的当前错误:

SyntaxError (/Users/philipengles/2016/january/ac_commonlit/commonlit/app/controllers/schools_controller.rb:13: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
...ool.where(zip_code: LIKE params[:zip_code])

很抱歉这么长的帖子,但我想给你全面了解我目前的状态。如果任何人有任何建议或任何与此材料相关的博客文章将是非常有用的。先感谢您。

1 个答案:

答案 0 :(得分:0)

您的ActiveRecord查询中出现语法错误:

@school_suggestions = School.where(zip_code: LIKE params[:zip_code])

ActiveRecord API不提供构建LIKE查询的方法,因此您需要使用带通配符的字符串条件:

@school_suggestions = School.where("zip_code LIKE ?", params[:zip_code])

另请read this part of the Rails documentation了解更多信息。