Daði Hall Daði Hall - 5 months ago 9
Ruby Question

search form not working and gives error in rails app

Im trying to implement a search field to an rails app I'm building to learn rails.

When I make a search rails throw back this error.

ActiveRecord::StatementInvalid in ProductsController#search


PG::UndefinedColumn: ERROR: column "short_description" does not exist LINE 1: ...WHERE (name LIKE '%%' or description LIKE '%%' or short_desc... ^ : SELECT "products".* FROM "products" WHERE (name LIKE '%%' or description LIKE '%%' or short_description LIKE '%%')


In my _navbar.html.erb I have this code

<%= form_tag search_products_path, class: 'navbar-form navbar-right' do %>
<%= search_field_tag class: 'form-control', :id => 'searchbar', :placeholder =>'Search', :name => "query" %>
<%= submit_tag "Submit", class: 'btn btn-default', :name => nil %>
<% end %>


and in the products_controller.rb I have this code

def search
@q = "%#{params[:query]}%"
@products = Product.where("name LIKE ? or description LIKE ? or short_description LIKE ?", @q, @q, @q)
@categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct
end


And in the routes.rb I have this line of code

post 'products/search' => 'products#search', as: 'search_products'


Can someone please help me with this, I´m not experienced enough to figure this out by my self.

Answer

In the products controller you have this ActiveRecord code:

Product.where("name LIKE ? or description LIKE ? or short_description LIKE ?", @q, @q, @q)

In that SQL string you're referencing short_description, which is apparently not a column on the products_table.

You can generate a migration to add the column like so:

rails g migration AddShortDescriptionToProducts short_description:text
rake db:migrate
Comments