基于Semantic UI的下拉输入框

<form class="ui form form-horizontal" style="margin-top: 8px;margin-right: 50px;", id="top_search_form">
        <div class="column">
          <div class="ui search">
            <div class="ui icon input">
                <input type="text" class="prompt" placeholder="搜索 产品、公司名称" name="top_search" style="width: 300px" >
                <i class="circular search link icon"></i>
            </div>
          </div>
        </div>
      </form>


$("#top_search_form").find(".ui.search").search({
    apiSettings: {
      url: '/top_search?q={query}'
    },
    fields:{
      title: 'valid_name'
    },
    searchDelay: 500,
    minCharacters : 2,
    onSelect: function(result, response){
      if(result.class_name == 'Chemical'){
        window.open("/chemicals/" + result.id);
      }else{
        window.open("/companies/" + result.id);
      }
    }
  });


def top_search
    results = []
    if params[:q].present?
      q = params[:q].to_s.strip
      if m = /(\d+-\d+-\d+)/.match(q)
        chemical = ::Chemical.find_by(cas: m[1] )
        results << chemical.as_json(only: :id, methods: [:valid_name, :class_name]) if chemical.present?
      else
        company_ids = User.select("company_id").joins(:contact).where("users.email = :q or users.mobile = :q or contacts.qq = :q", q: q).pluck(:company_id)
        if company_ids.present?
          companies = ::Company.where(certification: :certified).where(id: company_ids)
        else
          companies = ::Company.left_joins(:company_aliases).certified.where("companies.name_cn like :q or companies.name like :q or company_aliases.name like :q", {q: "%#{q}%"})
        end
        if companies.present?
          results = companies.order(:name_cn).distinct.limit(10).as_json(only: :id, methods: [:valid_name, :class_name])
        else
          chemical_ids = ::ChemicalAlias.select(:chemical_id).where("chemical_aliases.name like ?", "%#{q}%").limit(10).pluck(:chemical_id)
          if chemical_ids.present?
            chemicals = ::Chemical.select(:id, :cas, :name, :name_cn).where("chemicals.name like :q or chemicals.name_cn like :q or chemicals.id in (#{chemical_ids.join(',')}) ", q: "%#{q}%").limit(10)
          else
            chemicals = ::Chemical.select(:id, :cas, :name, :name_cn).where("chemicals.name like :q or chemicals.name_cn like :q", q: "%#{q}%").limit(10)
          end
          results = chemicals.as_json(only: :id, methods: [:valid_name, :class_name])
        end
      end
    end
    respond_with( {results: results})
  end

猜你喜欢

转载自schooltop.iteye.com/blog/2425246