Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Activerecord Rails 4搜索栏_Activerecord_Ruby On Rails 4 - Fatal编程技术网

Activerecord Rails 4搜索栏

Activerecord Rails 4搜索栏,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我正在尝试在Rails 4应用程序中创建搜索栏。我是我的用户db有“名称”和“电子邮件”列供用户使用-我希望用户能够通过名称或id搜索其他用户 我现在得到的是: ActiveRecord::RecordNotFound in UsersController#index Couldn't find all Users with 'id': (all, {:conditions=>["name LIKE ?", "%hi@example.com%"]}) (found 0 results, b

我正在尝试在Rails 4应用程序中创建搜索栏。我是我的用户db有“名称”和“电子邮件”列供用户使用-我希望用户能够通过名称或id搜索其他用户

我现在得到的是:

ActiveRecord::RecordNotFound in UsersController#index
Couldn't find all Users with 'id': (all, {:conditions=>["name LIKE ?", "%hi@example.com%"]}) (found 0 results, but was looking for 2)
有人知道我做错了什么吗?我看过railscasts和一些论坛等,但目前还不能超越这一点

index.html.erb:

<% form_tag users_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>
用户\u controller.rb:

  def index
    @users = User.search(params[:search])
  end
routes.rb:

  get     'search'   =>      'users#index'
在rails中搜索

默认情况下,rails不支持全文搜索。Activerecord finder始终使用主键(即id)查找记录。 因此,我们需要一些其他的宝石或应用,如太阳黑子、elasticsearch等

我将在这里演示如何使用太阳黑子solr

在应用程序的gem文件中,只需添加以下代码。。。 . 宝石“太阳黑子轨道”

group :development do
    gem 'sunspot_solr'
end
并在终端使用 捆绑安装 轨道g太阳黑子轨道:安装

这将添加solr并创建config/sunspot.yml文件

rake太阳黑子:solr:开始 rake太阳黑子:重新索引

在模型中编辑user.rb lile app/model/user.rb

Class User < ActiveRecord::Base
    searchable do
        text :name, :email
    end
end
制作表单以接受用户输入

<%= label_tag(:search, "Search for:") %>
  <%= text_field_tag(:search) %>
  <%= submit_tag("Search") %>
<% end %>
您使用的是Rails 4吗?查找:所有。。。这是一种古老的做事方式。“查找”现在只接受ID。使用:

def self.search(search)
  if search.present?
    where('name LIKE ?', "%#{search}%")
  else
    where(true)
  end
end

也在场吗?将针对零和空白进行测试。请记住,根据您的数据库,LIKE可能会非常慢。

谢谢@amritesh!我一直在寻找一个不涉及宝石的解决方案
<%= label_tag(:search, "Search for:") %>
  <%= text_field_tag(:search) %>
  <%= submit_tag("Search") %>
<% end %>
def self.search(search)
  if search.present?
    where('name LIKE ?', "%#{search}%")
  else
    where(true)
  end
end