【问题标题】:Rails Search - Passes params, doesn't return results (error)Rails 搜索 - 传递参数,不返回结果(错误)
【发布时间】:2014-08-09 02:04:23
【问题描述】:

我正在尝试在我的 Rails 应用程序上进行简单的搜索。我只有两个选择器可供选择:(a) kind 和 (b) location_id。表单显示,值可选,参数在 url 中传递。但是,即使有匹配的内容,当我提交时也没有任何显示。我签入了我的活动管理员,并且有一些地方可以匹配搜索参数。

这是我的 places_controller.rb

def index
   @places = Place.search(params[:kind],[:location_id])
end

我的place.rb

def self.search(kind, location_id)
  return scoped unless kind.present? || location_id.present?
  where(['kind = ? AND location_id = ?', kind, location_id])
end

和我的搜索表单_home.html.erb

<%= form_tag places_path, :method => 'get' do %>
    <form class="form-inline text-center" role="form" action="/places">
        <div class="form-group">
           <%= label_tag :kind %>
           <%= select_tag :kind, options_for_select([['beer','0'],['chocolate','1'],['cocktail','2'], ['coffee','3'], ['tea','4'], ['wine','5'], ['juice','6']]), class: "form-control" %>
         /div>
 <br>
         <div class="form-group">
            <%= label_tag :location_id %><br>
            <%= select_tag :location_id, options_for_select([['Houston','0'],['San Francisco','1'],['Santiago','2'], ['Valparaiso','3'], ['Rio de Janeiro','4'], ['Milan','5'], ['Palo Alto','6'], ['Las Vegas','7'], ['New York','8'], ['San Diego','9']]), class: "form-control" %>
          </div>
 <br>
 <br>
          <div class="actions">
          <span itemprop="significantLink">
          <%= submit_tag 'Search', :name => nil, class: "btn btn-default" %>
          </span>
          </div>
 </form>
 <% end %>

不胜感激!环顾了一堆 SO/Railscast,但不知道该怎么做!

【问题讨论】:

  • 在您的代码中,您在哪里使用您为搜索结果设置的@places 变量?
  • 在我的 index.html.erb /places

标签: ruby-on-rails ruby search query-parameters


【解决方案1】:

首先我看到了一些错误。定义索引如下:

def index
   @places = Place.search(params[:kind], params[:location_id])
end

另外,您可能希望实际使用 respond_to 块来协商响应应该是什么,例如 html 或 json。

respond_to do |format|
  format.html { YOUR STUFF HERE }
  format.json { YOUR STUFF HERE }
end

我最好的建议是在@places 赋值之后放置一个debugger 语句,这样您就可以实际调试正在发生的事情并查看正在发生的事情。

【讨论】:

  • 谢谢!那行得通!你的意思是这样的吗?我对编码很陌生,所以有点困惑。 def index @places = Place.search(params[:kind], params[:location_id]) respond_to do |format| if @place.search format.html {redirect_to @places} format.json {redirect_to @places} else format.html {redirect_to @places.all} format.json {redirect_to @places.all} end end end 我在后面加空格@'s for SO
  • 首先。当您读取从视图传递的参数时,您需要始终使用 params[:VALUE]。值总是作为散列从表单传递回控制器。不管是 GET、POST、PUT、Form 还是 Querystring。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多