-1

在 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

我必须根据所选城市搜索和显示酒店。但此代码不起作用。

4

3 回答 3

0

您的where不需要[]括号:

@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

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

于 2013-07-11T09:39:23.540 回答
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
于 2013-07-11T09:43:23.650 回答
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')
于 2013-07-11T10:08:14.883 回答