多条件查询

def cad_enterprises_search
    sql = ""
    @cad_enterprises1 = Array.new
    name = params[:name] unless params[:name].nil?
    user_id = params[:user_id] unless params[:user_id].nil?
    tel = params[:tel] unless params[:tel].nil?
    website= params[:website] unless params[:website].nil?
    email= params[:email] unless params[:email].nil?
    city_id = params[:city_id] unless params[:city_id].nil?
   
    unless name.nil? || name.empty?
      sql += "  company like '%#{name}%' "
    end 
   
    unless city_id.nil? || city_id.empty?
      sql += " and city_id = #{city_id} "
    end
   
    unless user_id.nil? || user_id.empty?
      sql += " and user_id = #{user_id} "
    end
   
    unless tel.nil? || tel.empty?
      sql += " and tel = '#{tel}' "
    end   
   
    unless website.nil? || website.empty?
      sql += " and website = '#{website}' "
    end
   
      unless email.nil? || email.empty?
      sql += " and email = '#{email}' "
    end
   
    @cad_enterprises1= CadEnterprise.find_by_sql("select * from cad_enterprises where #{sql} ")
     
    @cad_enterprises2=[]
    cad_contact_ids = params[cad_enterprise][cad_contact_ids] unless params[cad_enterprise][cad_contact_ids].nil?
    trade_ids = params[cad_enterprise][trade_ids] unless params[cad_enterprise][trade_ids].nil?
    nposition_ids = params[cad_enterprise][:nposition_ids] unless params[cad_enterprise][:nposition_ids].nil?
  
    unless cad_contact_ids.nil? || cad_contact_ids.empty?
      for cad_contact_id in cad_contact_ids
       cad_contact=Trade.find(cad_contact_id)
       @cad_enterprises2 << cad_contact.cad_enterprises
      end
    end
  
    unless trade_ids.nil? || trade_ids.empty?
      for trade_id in trade_ids
       trade=Trade.find(trade_id)
       @cad_enterprises2 << trade.cad_enterprises
      end
    end
   
    unless nposition_ids.nil? || nposition_ids.empty?
      for nposition_id in nposition_ids
      nposition=Nposition.find(nposition_id)
      @cad_enterprises2 << nposition.cad_enterprises
      end
    end
              
     if @cad_enterprises2==[]
       @cad_enterprises=@cad_enterprises1
     else
       @cad_enterprises=@cad_enterprises1&@cad_enterprises2
     end  
   
     @cad_enterprises = @cad_enterprises.paginate( :page => params[:page],:per_page => 30, rder =>'convert(created_at using gbk)desc',:order => 'convert(company using gbk)')

  end

你可能感兴趣的:(多条件查询)