Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search in Rails

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

posts_controller.rb:

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

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>

and 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: I want to search by 'title'.

like image 408
Dmytro Vasin Avatar asked Aug 17 '12 17:08

Dmytro Vasin


1 Answers

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.

A Simple search form

Advanced search form

Searching with AJAX

Powerful search functionality with the Sunspot gem

List of the most popular search tools for Ruby

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

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

Tire

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

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

like image 156
Aaron Gray Avatar answered Oct 02 '22 09:10

Aaron Gray