Rails和Angularjs在自动完成字段上缓慢查询结果

时间:2015-03-16 15:31:57

标签: mysql ruby-on-rails angularjs ruby-on-rails-4 activerecord

我正在使用带角度的rails,我已经创建了一个实时搜索输入字段。我正在排除故障,为什么查询在浏览器内需要大约1.5秒,但直接从mysql控制台运行完全相同的查询时只需23毫秒。任何帮助将不胜感激。

这就是我所拥有的:

products_controller.rb

def getProducts
  @product_results=Product.searchProduct(params[:term])
  respond_to do |format|
    format.json { render json: @product_results}
  end
end

product.rb

def self.searchProduct(search)
  if search
    where('product_name LIKE :column or product_code like :column', :column => "%#{search}%")
  else
    scoped
  end
end

导致查询:

SELECT * `products` 
WHERE (product_name LIKE '%example%' or product_code like '%example%')

的routes.rb

resources :products do
  get :getProducts, :on => :collection
end

product.html:这就是魔术的用武之地。我使用了这些人开发的指令https://github.com/ghiden/angucomplete-alt

<angucomplete-alt id="ex1"
   placeholder="Search Products"
   pause="100"
   selected-object="selectedProduct"
   remote-url="products/getProducts?term="
   remote-url-data-field="products"
   title-field="product_name"
   minlength="1"
   input-class="form-control form-control-small">
 </angucomplete-alt>

这是我所注意到的。如果您在输入字段中键入内容并且查询被中断,则会重置查询。不确定这是否与它有关。视图呈现为.6秒,但ActiveRecord仍需要1秒才能完成。

控制台:

Started GET "/products/getProducts?term=12%20oz" for 127.0.0.1 at 2015-03-16 11:25:07 -0400
[2015-03-16 11:25:07] ERROR Errno::ECONNRESET: Connection reset by peer @ io_fillbuf - fd:20
/Users/ctilley83/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:80:in `eof?'
/Users/ctilley83/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:80:in `run'
/Users/ctilley83/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'
Processing by ProductsController#getProducts as JSON
  Parameters: {"term"=>"12 oz"}
  Product Load (1.0ms)  SELECT * FROM `products` WHERE (product_name LIKE '%12 oz%' or product_code like '%12 oz%')
Completed 200 OK in 622ms (Views: 620.6ms | ActiveRecord: 1.0ms)

0 个答案:

没有答案