Search code examples
ruby-on-railssearch-form

rails search form 'no such column: name' error


I'm trying to implement a simple search box in my index view but it gave me this error:

    SQLite3::SQLException: no such column: name: SELECT "tickets".* FROM "tickets"  WHERE (name LIKE '%s%')

I can't figure out why this is and how do I correct it. Below is my MVC

View

<h1>Listing tickets</h1>
<%= form_tag tickets_path, :method => 'get' do %>
    <p>
      <%= text_field_tag :search, params[:search] %>
      <%= submit_tag 'Search' %>
    </p>
<% end %>
<table>
  <tr>
  ...
  </tr>

<% @tickets.each do |ticket| %>
  <tr>
    <td><%= ticket.caller_name %></td>
    <td><%= ticket.called_date %></td>
    <td><%= ticket.problem %></td>
   ...
<% end %>
</table>

Model

class Ticket < ActiveRecord::Base
  attr_accessible :called_date, :caller_name, :problem
  has_many :logs, :dependent=>:destroy
  def self.search(search)
    if search
      find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
  end
end

Controller

class TicketsController < ApplicationController
  def index
    @tickets = Ticket.all
    @tickets = Ticket.search(params[:search])
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @tickets }
    end
  end

Solution

  • You are trying to query the column name that does not exist on your tickets table. So just replace it with a column that does exist, caller_name in your case. Replace the following line:

    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    

    with

    find(:all, :conditions => ['caller_name LIKE ?', "%#{search}%"])