2016-02-12 239 views
0

我想構建一個應用程序,用戶可以選擇多個複選框。 我需要建立一個動態查詢來從數據庫中獲取數據但出錯。 這裏是我的動態查詢的控制器代碼。基於用戶複選框選擇的動態查詢創建

if params[:food_type] != nil 
     params[:food_type].each do |food_type| 
     query_string << ' OR ' unless query_string.empty? 
     query_string << 'food_type = ?' 
     query_values << food_type 

    end 
    end 
    wrev["wrev"] = SearchResult.where(query_string, query_values) 
     @pgresults << wrev 
     wrev = {} 

    respond_to do |format| 
    format.html 
    format.json { render json: @pgresults } 

我得到的錯誤是「準備好的語句無效(錯號碼綁定變量)。 我已經定義

query_string = String.new 
    query_values = [] 

回答

0

你可以通過‘QUERY_STRING’的一部分‘作爲一個數組query_values’ ,見method where documentation

if params[:food_type] != nil 
     params[:food_type].each do |food_type| 
     query_string << ' OR ' unless query_string.empty? 
     query_string << 'food_type = ?' 
     query_values << food_type 

    end 
    end 
    query_values.unshift(query_string) #add the string at the beginning of the array 
    wrev["wrev"] = SearchResult.where(query_values) #passing the arrary with the query string and the values as just one array. 
     @pgresults << wrev 
     wrev = {} 

    respond_to do |format| 
    format.html 
    format.json { render json: @pgresults }