在Rails中搜索

Dmy*_*sin 17 search ruby-on-rails

我有一个"帖子"表,其中包含title和的属性body.

posts_controller.rb:

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

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>
Run Code Online (Sandbox Code Playgroud)

和post.rb

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

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

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| %>
Run Code Online (Sandbox Code Playgroud)

APD:我想按'标题'搜索.

Aar*_*ray 43

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

一个简单的搜索表单

高级搜索表单

使用AJAX搜索

太阳黑子宝石具有强大的搜索功能

Ruby最受欢迎的搜索工具列表

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

Elasticsearch因其具有的一些现代特性而越来越受欢迎,例如即时索引.它有一颗名为轮胎的红宝石宝石.绝对值得一看.

Elasticsearch

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

轮胎已经退役,并已被Elasticsearch-ruby取代

  • 它被重新命名为"退休" (6认同)

Mot*_*jha 10

Elasticsearch with gem searchkick

注意:searchkick也由轮胎贡献)让你更舒服的工作.

更多参考:

SearchKick


Adr*_*ann 9

对于来到这里并在Rails 4中寻找解决方案的人,请尝试以下示例:

帖子控制器:

class PostsController < ApplicationController
  def index
    if params[:search]
      @posts = Post.search(params[:search]).order("created_at DESC")
    else
      @posts = Post.all.order('created_at DESC')
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

邮政模式:

def self.search(search)
  # Title is for the above case, the OP incorrectly had 'name'
  where("title LIKE ?", "%#{search}%")
end
Run Code Online (Sandbox Code Playgroud)

index.html.erb与搜索表单保持不变:

<%= form_tag(posts_path, :method => "get", id: "search-form") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
  <%= submit_tag "Search" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

请注意,您使用的路径,控制器和列可能不同.