Search code examples
ruby-on-railsruby-on-rails-4searchproductsearchbar

Why the products search bar is not working? Rails 4


I have a simple search bar to find products by name and order the results alphabetical.

-----> products_controller.rb

  def index
    scope = Product
    if params[:search]
      scope = scope.search(params[:search])
    end
    if params[:ordering] && ordering = ORDERS[params[:ordering].to_i]
      scope = scope.order(ordering)
    end
    @products = Product.includes(:current_price).all.stock.order('id DESC')
    @product_detail = ProductDetail.new
  end

-----> product.rb

class Product < ActiveRecord::Base
    has_many :product_details
    has_many :prices
    has_one :current_price, -> {
    where('prices.id = (SELECT MAX(id) FROM prices p2 WHERE product_id = prices.product_id)') 
  }, class_name: 'Price'

  accepts_nested_attributes_for :prices 
  accepts_nested_attributes_for :product_details

  # It returns the products whose names contain one or more words that form the query
  def self.search(query)
    where(["name LIKE ?", "%#{query}%"])
  end

  # Returns a count with the available products on stock
  def self.stock()
    select('products.*, SUM(case when product_statuses.available=true then 1 else 0 end) as count')
    .joins('LEFT JOIN `product_details` `product_details` ON `product_details`.`product_id` = `products`.`id`')
    .joins('LEFT JOIN `product_statuses` ON `product_statuses`.`id` = `product_details`.`status`')
    .group('products.id')
  end

end

I don't know, I have a very similar code for my Customers controller and model to do a phonebook and It works.

The only different is the "stock" to calculate how many units are available on the inventory, and It's working good.

I really need help with search bar :( I already reviewed all my code and looks good.

Thanks to everyone


Solution

  • Why is your @product variable not using the scope you already defined. I think it should be @products = scope.includes(:current_price).all.stock.order('products.id DESC')

    Add products.id DESC instead of id DESC since the statement may be ambiguous to ActiveRecord. Also you will have to append products. to your orderng params.