2013-07-11 98 views
-1

工作在usrshow.html.erbWHERE條件不軌

<%= form_for userview_path, :method => 'get' do |f|%>  
<%= f.collection_select :city, Place.all, :id, :name, :prompt => 'select place' %> 
<%= text_field_tag :search %> 
<%= submit_tag "Search"%> 
<% end %> 

在hotels_controller

def usrshow 
    if params[:search].present? 
     @hotels = Hotel.where(["city_id = ? and hotels LIKE ?",params[:city], "%#{params[:search]}%"]) 
     else 
     @hotels = Hotel.all(:order => 'id DESC') 
    end 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render :json => @hotels } 
    end 
end 

我要搜索和顯示酒店根據所選擇的city.But這個代碼不加工。

+2

「不工作」是不夠的信息。你有錯誤嗎?這是什麼意思「它不工作」? –

+0

此代碼未搜索字段。它只返回空字段 –

+0

您是否在酒店表中有「酒店」或「名稱」字段? – Debadatt

回答

0

你不需要在你的其中[]括號:

@hotels = Hotel.where("city_id = ? and hotels LIKE ?",params[:city], "%#{params[:search]}%") 

指定您的錯誤。不工作是描述

您可以檢查SQL查詢在控制檯:

Hotel.where("city_id = ? and hotels LIKE ?",params[:city], "%#{params[:search]}%").to_sql 

它會告訴你確切的查詢。你可以運行你的數據庫並驗證結果。

0

使用的簡單搜索條件

def usrshow 
    if params[:search].present? 
    @hotels = Hotel.where("city_id = ? AND hotels LIKE ",params[:city],"%#{params[:search]}%").order('id DESC') 
     else 
     @hotels = Hotel.all(:order => 'id DESC') 
    end 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render :json => @hotels } 
    end 
end 
0

您的參數

Parameters: {"commit"=>"Search", "search"=>"m", "/userview"=>{"city"=>""}, "utf8"=>"✓"} 

手段params[:city]nil我認爲你必須使用params["/userview"]["city"]代替

@hotels = Hotel.where("city_id = ? AND hotels LIKE ", 
         params["/userview"]["city"], 
         "%#{params[:search]}%").order('id DESC')