【问题标题】:How to make dropdown select search field to work, when using the Ransack gem on Rails?在 Rails 上使用 Ransack gem 时,如何使下拉选择搜索字段起作用?
【发布时间】:2016-04-26 07:15:43
【问题描述】:

我在 Ruby on Rails 4.2.2 上使用 Ransack gem。

:name 字段搜索有效,但我无法让下拉选择字段正常工作。当我从下拉菜单中选择一个项目并按“搜索”时,我没有得到任何搜索结果。这是我在终端上得到的:

Started GET "/companies?utf8=%E2%9C%93&q%5Bname_cont%5D=&..." for ...
Processing by CompaniesController#index as HTML
Parameters: {"utf8"=>"✓", "q"=>{"name_cont"=>"", "category_eq"=>"7", "location_eq"=>""}, "commit"=>"Search"}
Company Load (0.3ms)  SELECT "companies".* FROM "companies"
CACHE (0.0ms)  SELECT "companies".* FROM "companies"
Company Load (0.1ms)  SELECT "companies".* FROM "companies" WHERE "companies"."category" = '7'
Rendered companies/index.html.erb within layouts/application
Completed 200 OK in 217ms 

这是我的 Companies_controller.rb

class CompaniesController < ApplicationController
  def index
    @search = Company.search(params[:q])
    @companies = @search.result
  end
end

这里是公司的 index.html.erb:

    <%= search_form_for @search do |f| %> 

       <div class="field">
         <%= f.label :name_cont, 'Company Name' %>
         <%= f.text_field :name_cont, class: 'form-control' %>
       </div>

       <div class="field">
         <%= f.label :category_eq, 'Category' %>
         <%= f.select :category_eq, options_from_collection_for_select(Company.all, "id", "category", @search.category_eq) %>
       </div>

       <div class="field">
         <%= f.label :location_eq, 'Location' %>
         <%= f.select :location_eq, options_from_collection_for_select(Company.all, "id", "location", @search.location_eq) %>
       </div>

      <div>  
        <%= f.submit "Search" %>
      </div>

  <% end %>

  <% @companies.each do |company| %>
  <tr>
    <td><%= company.name %></td>
    <td><%= company.category %></td>
    <td><%= company.location %></td>
  </tr>
<% end %>

我不知道为什么 :name 有效,但是 :category 和 :location 在搜索中没有显示任何内容?

【问题讨论】:

  • 你也可以发布Company 模型吗?
  • 我用你的变量替换了一个有效的ransack select的选项,请试试这个:&lt;%= f.select :location_eq, Company.all.pluck(:location, :id) %&gt;
  • 不幸的是没有工作,但感谢您的建议!我最终在 Railscast 教程的帮助下从头开始创建搜索,现在它可以工作了,但方式完全不同。

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


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多