cratag
cratag

Reputation: 122

Search function that looks within my previously created controller

I think this is a simple question but I couldn't find it. I've been following this guide to make a search function. The tutorial actually uses SQL and I'm using PostgreSQL, but I don't think that makes any difference.

Instead of looking for name in Store database, I want it to search for Plant_ID in my PlantTable database.

This is what the tutorial showed:

#app/controllers/page_controller.rb 

  def index
  end
  def search  
    if params[:search].blank?  
      redirect_to(root_path, alert: "Empty field!") and return  
    else  
      @parameter = params[:search].downcase  
      @results = Store.all.where("lower(name) LIKE :search", search: @parameter)  
    end  
  end
end

But I actually added it into my home controller and this was my final attempt

#app/controllers/home_controller.rb

class HomeController < ApplicationController
  def index
  end
  def search
    @plant_tables = PlantTable.all
    #So I can get PlantTable from a different controller  
    if params[:search].blank?  
      redirect_to(root_path, alert: "Empty field!") and return  
    else  
      @parameter = params[:search].downcase  
      @results = @plant_tables.all.where("Plant_ID LIKE :search", search: @parameter)
      #I removed lower() because my Plant_ID is written like this.  
    end  
  end
end

Added code to my routes.rb: get '/search' => 'pages#search', :as => 'search_page'

But in my app/views/home/search.html.erb...

<h3>Search Result</h3>  

    <% @results.each do |result| %>  
        <%= result.name %><br>  
    <% end %>

...I get the following error:

ActiveRecord::StatementInvalid in Home#search

PG::UndefinedColumn: ERROR:  column "plant_id" does not exist
LINE 1: ...ELECT "plant_tables".* FROM "plant_tables" WHERE (Plant_ID L...
                                                             ^
HINT:  Perhaps you meant to reference the column "plant_tables.Plant_ID".

Upvotes: 0

Views: 49

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33430

Due to the particular case in which your column name is you'll have to wrap it in quotes and cast it to text to perform a LIKE query:

PlantTable.where('"Plant_ID" LIKE ?', @parameter)

Notice;

  • Wrapping the column name in single quotes and the argument for where will not work.
  • You can remove the second all you're chaining on @results.

Upvotes: 2

Related Questions