Last Updated: February 25, 2016
·
426
· jmalley

Total Noob

I made a basic mistake today that eluded me for way too long. I have a list of movies, with a search field at the top. When I try to search for something, the page would refresh but look exactly the same. No errors, but the list of movies did not change to one that matched my search term. The bug would be obvious to someone more experienced, but I didn’t find it until after hours of inspecting, tweaking, and testing various aspects of my controllers and routes. Here’s the bug:

<% Movie.all.each do |movie| %>
  <h3><em><%= movie.title %></em> (<%= movie.year_released.to_s %>)</h3>
  <p><%= movie.description %> <%= link_to "EDIT", edit_movie_path(movie) %></p>
<% end %>

My list of movies was generated by listing all of the Movie objects in the database. This isn’t a bad thing, necessarily, and is a holdover instict from learning pure ruby. The problem with this is that it’s not taking its queues about what to display from the controller, so it doesn’t change to the search results properly. Here’s the index action in the controller:

def index
  @movies = Movie.search(params[:q]).order("created_at DESC") || Movie.all
end

So that means the index page should take the @movies instance variable, since that’s the one being conditionally set here.

<% @movies.each do |movie| %>
  <h3><em><%= movie.title %></em> (<%= movie.year_released.to_s %>)</h3>
  <p><%= movie.description %> <%= link_to "EDIT", edit_movie_path(movie) %></p>
<% end %>

Works like a charm!