条件不适用于铁路

时间:2013-07-11 09:31:16

标签: ruby-on-rails

在usrshow.html.erb

<%= 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

我必须根据所选城市搜索和显示酒店。但此代码无效。

3 个答案:

答案 0 :(得分: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

它会显示确切的查询。您可以运行数据库并验证结果。

答案 1 :(得分: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

答案 2 :(得分: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')