为什么产品搜索栏不起作用? Rails 4

Why the products search bar is not working? Rails 4

我有一个简单的搜索栏,可以按名称查找产品并按字母顺序排列结果。

-----> 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

我不知道,我的 Customers 控制器和模型有一个非常相似的代码来制作电话簿并且它有效。

唯一不同的是 "stock" 计算库存中可用的单位数量,而且效果很好。

我真的需要搜索栏方面的帮助 :( 我已经检查了我的所有代码并且看起来不错。

感谢大家

为什么您的 @product 变量没有使用您已经定义的 scope。我觉得应该是@products = scope.includes(:current_price).all.stock.order('products.id DESC')

添加 products.id DESC 而不是 id DESC 因为该语句对于 ActiveRecord 可能不明确。您还必须附加产品。到您的订购参数。