-1
我有一個簡單的搜索欄,按名稱查找產品,並按字母順序排列結果。爲什麼產品搜索欄不起作用? 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
我不知道,我有一個非常類似的代碼我客戶控制器和模型做一個電話簿,它的工作原理。
唯一不同的是「庫存」來計算清單上有多少單位可用,並且它運作良好。
我真的需要搜索欄幫助:(我已經審查我的代碼,並期待良好。
感謝大家爲什麼你@product
變量未使用
我用你的第一個建議,我收到以下錯誤:產品中的ActiveRecord :: StatementInvalid#index –
關於你的第二個建議,我不想區分大小寫的搜索 –
我已經更新了答案。我猜你需要添加'products.id DESC'而不是'id DESC',因爲該語句可能對ActiveRecord不明確。你也必須將'products.'附加到你的訂單參數中。 –