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