首页 > 解决方案 > rails autocomplete gem 以限制对语言环境参数的搜索

问题描述

自动完成 gem 调用以下操作进行处理

Started GET "/nations/autocomplete_nationtranslation_name?locale=en&term=erm"

Nationtranslation 表有一个索引列

t.string   "locale"

模型定义为:

autocomplete :nationtranslation, :nome, full: true
autocomplete :nationtranslation, :nome, full: true, :extra_data => [:locale]

两者都返回所有语言环境的所有可能值,而

autocomplete :nationtranslation, :nome, full: true, :extra_data => params[:locale]

返回ActionController::RoutingError (undefined local variable or method 'params' for NationsController:Class

自动完成如何在
locale = params[:locale]范围内运行搜索

标签: ruby-on-railsautocomplete

解决方案


我看到的唯一方法是提供您自己的控制器操作方法,该方法默认由rails-jquery-autocompletegem 生成。

class NationsController < ApplicationController

  # you don't really need this anymore
  # autocomplete :nationtranslation, :name

  def autocomplete_nationtranslation_name
    translations = Nationtranslation.where("name LIKE ? AND locale = ?", 
                                           "%#{params[:term]}%", 
                                           params[:locale])
                                    .order(:name)
    render json: translations.map { |t| {id: t.id, label: t.name, value: t.name} }    
  end
end

推荐阅读