user3576036
user3576036

Reputation: 1425

Simple search not working on rails app

I know I might be missing something here. I am following rails casts here.

I have model called Production with a name column.

In my controller I added a new method for searching as follows:

productions_controller.rb

  def index
   @productions =Production.all
  end

  def search
    if params[:search]
      @productions = Production.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])
    else
      @productions = Production.all
    end
  end

And then I added this action in route file:

resources :productions do
    collection do
        get 'search'
    end
  end

I gave a search field in index.html.erb

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

And then I created a landing for search action

search.html.erb

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Director</th>
      <th>Status</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @productions.each do |production| %>
      <tr>
        <td><%= production.name %></td>
        <td><%= production.director %></td>
        <td><%= production.status %></td>
        <td><%= link_to 'Show', production %></td>
        <td><%= link_to 'Edit', edit_production_path(production) %></td>
        <td><%= link_to 'Destroy', production, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

productions table

create_table "productions", force: :cascade do |t|
    t.string "name"
    t.string "director"
    t.integer "status"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

Now when I search for a keyword in the name table I am getting all the names in the table, even which are no close to the keyword entered.

Upvotes: 0

Views: 28

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

You're using Rails 2.3 query syntax, this rails cast is terribly outdated. It should be more like:

@productions = Production.where('productions.name like ?', "%#{params[:search]}%")

Also, you have it in search action, while you should put this code in index action, since the search form routes to index.

If you want it to stay in search action, you should change your form path:

 <%= form_tag [:search, :productions], :method => 'get' do %>

Upvotes: 1

Related Questions