在rails中搜索问题

时间:2014-11-08 07:14:31

标签: ruby-on-rails ruby-on-rails-4

我有:

<%= form_tag :controller => 'hotels',:search=>params[:search],method: :post do %>
<div id="box" style="width: 400px;margin-left: 33%">
<%= text_field_tag :search, nil, :class => 'search-box', :required => true,:placeholder=>'Type Your City Name(Bhubaneswar,Cuttack)'%>
</div>

<%= submit_tag "Search", :name=>'btnsearch',class: "btnSearch",:method=>'post'%>

</div>
<%end%>

在控制器中:

def index

@hotels= Hotel.where('hotel_location LIKE ?',"%#{params[:search]}%").includes(:offers)

在我的路线中:

get 'hotels/index'

match ':controller(/:action(/:id))(.:option)',:via=>[:get,:post]

点击搜索按钮后,我进入我的日志:

Started POST "/hotels/index?method=post" for 127.0.0.1 at 2014-11-08 12:32:07 +0530 Processing by HotelsController#index as HTML

单击搜索按钮后,其工作正常,但当我刷新页面/hotels/index?method=post时,过滤值(params [:search])会丢失,页面会显示数据库中存在的所有酒店table.Kindly帮我解决这个问题。

3 个答案:

答案 0 :(得分:0)

您的form_tag声明应为:

<%= form_tag :controller => 'hotels', :action => 'index' do %>

<% end %>

<%= form_tag hotels_path do %>

<% end %>

答案 1 :(得分:0)

您的表单应如下所示:

<%= form_tag hotels_path do %>
  <div id="box" style="width: 400px;margin-left: 33%">
    <%= text_field_tag :search, nil, :class => 'search-box', :required => true,:placeholder=>'Type Your City Name(Bhubaneswar,Cuttack)'%>
  </div>
  <%= submit_tag "Search", :name=>'btnsearch',class: "btnSearch",:method=>'post'%>
<%end%>

首次请求您的家庭控制器时,您可能需要所有酒店。所以你的控制器应该是:

def index 
  if params[:search].present? ? @hotels= Hotel.where('hotel_location LIKE ?',"%#{params[:search]}%").includes(:offers) : Hotel.includes(:offers) 
end

答案 2 :(得分:0)

对于记录text_field_tag采用字符串而不是符号http://apidock.com/rails/ActionView/Helpers/FormTagHelper/text_field_tag。由于您使用索引作为控制器,我建议您使用GET方法method: :get。 Google的搜索使用GET方法进行搜索,这就是您在网址中看到查询的原因

<%= form_tag hotels_path, method: :get do %>
  <div id="box" style="width: 400px;margin-left: 33%">
    <%= text_field_tag 'hotels[search]', nil, class: 'search-box', required: true, placeholder: 'Type Your City Name(Bhubaneswar,Cuttack)' %>
  </div>
  <%= submit_tag "Search", name: 'btnsearch', class: "btnSearch" %>
<% end %>

您无需在提交按钮中设置该方法,该方法已在form_tagform_for处理。

对于Rails 4,你会想要拥有strong_params,所以你应该有一个私人方法:

private
def hotels_params
  params.require(:hotel).permit(:search)
end

然后在您的控制器中,您可以将搜索参数更改为:

def index
  @hotels= Hotel.where('hotel_location LIKE ?',"%#{hotels_params[:search]}%").includes(:offers)

虽然我不喜欢在控制器中使用模型逻辑。我相信你应该把它移到你的模型本身。有关于此的大量在线文档。通过在名为@hotels = Hotel.similar_to(hotels_params['search'])的模型中调用自己的查询方法,similar_to会更好。

此外,您应该记住,在查看索引时,不会总是成为搜索参数。您可以在@hotels上hotels_params.has_key? 'search'或设置或等于设置。

@hotels = Hotel.similar_to(hotels_params['search']) ||= [Hotel.new]