Search code examples
ruby-on-railsruby-on-rails-4search-form

Rails Runtime Error in Controller#Index - Unsupported: Symbol


I've implemented a couple of different search forms in my app trying to achieve one specific action (input object ID and go straight to the Show Page for that instance), and I got fairly close on this one until I ran into an Unsupported: Symbol Runtime error for Cards#Index.

here is the search form (I just dropped it into layouts/application.html.erb:

<%= form_tag(cards_path, :method => "get") do %>
  <div class="input-append">
    <%= text_field_tag :search, params[:search], class: "span2", placeholder: "Search Cards" %>
    <button class="btn" type="submit"><i class="icon-search"></i></button>
  </div>
<% end %>

And here is my cards_controller.rb index action:

  def index
    if params[:search]
      @cards = Card.search(params[:search]).order("created_at DESC")
    else
      @cards = Card.order("created_at DESC")
    end
  end

  def show
  end

  private

  def set_card
    @card = Card.find(params[:id])
  end

  def card_params
    params.require(:card).permit(:title, :description)
  end

and model card.rb

class Card < ActiveRecord::Base 
  validates :title, presence: true, uniqueness: true
  validates :description, presence: true

  def self.search(query)
    where(:id, query)
  end
end

I was using where("title like ?", "%#{query}%") for the model, but I read that crafting sql queries this way was a security risk and I was also looking for exact matches.

So what is preventing the view from recognizing the id parameter passed by the search?


Solution

  • There's nothing wrong with your view - the problem is your search method, which does

    where(:id, query)
    

    Which just isn't a valid use of where.

    It should be

    where(id: query)
    

    Or, slightly more old school:

    where("id = ?", query )