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

亚历杭德罗·阿劳霍(Alejandro Araujo)

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

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

我不知道,我有一个与我的客户控制器和模型非常相似的代码来制作电话簿,并且可以正常工作。

唯一的不同是“库存”,用于计算库存中有多少单位可用,并且运行良好。

我确实需要搜索栏的帮助:(我已经检查了所有代码,看起来不错。

谢谢大家

我们

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

添加products.idDESC而不是,id DESC因为该语句可能与ActiveRecord不明确。另外,您将不得不附加产品。到您的orderng参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章