在 Rails 中搜索 [英] Search in Rails

查看:70
本文介绍了在 Rails 中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帖子"表,其属性包括titlebody.

I have a table of "posts" with attributes that include title and body.

posts_controller.rb:

posts_controller.rb:

class PostsController < ApplicationController
  def index
    @posts = Post.search(params[:search], params[:id])
  end
end

index.html.erb:

index.html.erb:

 <%= form_tag posts_path, :method => 'get'  do %>
   <%= text_field_tag :search, params[:search]%>
   <%= submit_tag "Search", :name => nil  %>
 <% end %>

<hr />
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>
 <tr>
  <td><hr></td>
  <td><hr></td>
</tr>
  <% @posts.each do |post| %>

    <tr>
      <td><%= post.title %></td>
      <td><%= post.text %></td>
      <td><%= link_to 'Show', :action => :show, :id => post.id %></td>
      <td><%= link_to 'Edit', :action => :edit, :id => post.id %></td>
      <td><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :confirm => 'Are you sure?' %></td>
    </tr>
    <tr>
      <td><hr></td>
      <td><hr></td>
    </tr>
  <% end %>
</table>

和 post.rb

def self.search(search, id)
 if search
   where(['name LIKE ?', "%#{search}%"])
 else
  scoped
 end
end

当我提交搜索参数时,我收到一条错误消息:

When I submit the search params, I get an error message:

ActiveRecord::StatementInvalid in Posts#index 
SQLite3::SQLException: no such column: name: SELECT "posts".* FROM "posts"  WHERE (name LIKE '%lorem%') 

Extracted source (around line #23):

23:   <% @posts.each do |post| %>

APD:我想按标题"搜索.

APD: I want to search by 'title'.

推荐答案

虽然这不是您问题的直接答案,但这里有一些资源可以帮助您学习搜索并在您的 Rails 应用程序中实现它.

Although this is not a direct answer to your question, here are some resources that may help you as you are learning about search and getting it implemented in your Rails app.

一个简单的搜索表单

高级搜索表单

使用 AJAX 搜索

Sunspot gem 的强大搜索功能

最流行的 Ruby 搜索工具列表

--------------更新----------------

---------------UPDATE----------------

由于 Elasticsearch 具有一些现代功能,例如即时索引,它越来越受欢迎.它有一颗名为轮胎"的红宝石.绝对值得一看.

Elasticsearch has been growing in popularity due to some modern awesomeness that it has, such as instant indexing. It has a ruby gem named tire. Definitely worth a look.

Elasticsearch

轮胎

--------------更新 2----------------

---------------UPDATE 2----------------

Tire 已退役,并已替换为 Elasticsearch-ruby

Tire has been retired, and has been replaced by Elasticsearch-ruby

这篇关于在 Rails 中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆