导航栏中的搜索表单不呈现任何内容

时间:2019-01-09 10:49:50

标签: ruby-on-rails

我的导航栏中有一个搜索表

The selector :not(.myclass) is invalid

在我的 product_controller.rb

  <%= simple_form_for :query, url: clients_products_path, method: :get,  wrapper: :inline_form, html: {class: 'form-inline'} do |f| %>
    <%= f.input  :keyword, placeholder: "Recherche" %>
    <%= f.submit "Valider" %>
  <% end %>

结束

我的查询似乎是正确的,因为我可以在Rails控制台中找到产品。 但它在product#index中不显示任何内容... 我在哪里错了?

  

更新

所有产品均显示良好,当我查询时一切都消失了 clients / products / index.html.erb

class Clients::ProductsController < ApplicationController


def index
  filter_products if params[:query].present?
  @products ||= Product.all
end

private

def filter_products
  return if params[:query].blank?
  @products = Product.where('lower(title) LIKE ?', params[:query][:keyword]) if params[:query][:keyword].present?
end

这是结果

<% @products.each do |product| %>
    <%= link_to clients_product_path(product) do  %>
        <%= image_tag(product.attachments.first.url) %>
        <%= product.title %>
        <%= product.price %>
    <% end %>
<% end %>

2 个答案:

答案 0 :(得分:1)

我相信您的问题就在这里:

@products = Product.where('lower(title) LIKE ?', params[:query][:keyword])

您需要使用%附加,附加或包装查询。例如:

@products = Product.where('lower(title) LIKE ?', "%#{params[:query][:keyword]}%")
# Think it's the above, though could be the following:
# @products = Product.where('lower(title) LIKE "%?%"', params[:query][:keyword])

如果您读过SQL的LIKE运算符,则%的操作类似于通配符。没有这些,您将搜索的是完全匹配的内容,而不是标题中包含的短语。 Docs are here

给个机会,让我知道你过得怎么样。

答案 1 :(得分:0)

首先,您要检查params[:query]两次(一次调用filter_products并在该函数中第二次检查)

您的filter_products函数存在问题。

在执行@products ||= Product.all时,如果查询返回空关系,则会得到空白ActiveRecordRelation。换句话说,如果@productsquery[:keyword]不匹配,title将始终为空白。

尝试将索引函数更改为:

def index
  @products = Product.where('lower(title) LIKE %?%', params[:query][:keyword].downcase) if params[:query][:keyword].present?
  puts @products
  @products ||= Product.all
end

如果仍然返回空白,则尝试打印@products变量。