我想在我的网站上实现一个简单的搜索功能。目前,当我使用我的搜索栏时它会起作用,但是如果找不到结果,那么它将拉出一个空白页面。我正在使用PostgreSQL
这是我在recipes / index.html.erb中的表单
<%= form_with(url: recipes_path, method: :get, local: true) do |form| %>
<%= form.text_field(:term, {class: 'form-control', type:'search',
arialabel:'search', placeholder: 'search by recipe name'})%>
<%= form.submit 'Search', class: 'btn btn-dark bg-dark' %>
<% end %>
这是我在recipes_controller.rb中的控制器索引操作
def index
@recipes = if params[:term]
Recipe.where('name LIKE ?', "%#{params[:term]}")
else
Recipe.all
end
@categories = Category.all
end
我想将用户重定向回索引视图,并显示一条消息,上面写着“找不到食谱,请搜索不同的食谱”。
在您的索引文件中
<%= form_tag('/recepies/', :method => :get, :role => 'form') do %>
<%= text_field_tag :term, :class => "form-control", :placeholder => "Search"%>
<button class='glyphicon glyphicon-search' type="search">
</button>
<% end %>
在你的控制器中,
def index
if params[:term].present?
@recipes = Recepie.all
@recipes = @recipes.find_term(params[:term].strip) if params[:term].present?
if @recipes.blank? {
flash[:notice] = 'the recipe was not found, please search for a different recipe.'
}
end
else
@recipes = Recepie.all
end
end
在你的模型中,
def self.find_term(term)
recipes = all
recipes = posts.where("recipes.term= ?", term)
end
当我使用我的搜索栏时它会起作用,但是如果找不到结果那么它会拉出一个空白页面。
所以你的搜索工作但没有结果。
我想将用户重定向回索引视图,并显示一条消息,上面写着“找不到食谱,请搜索不同的食谱”。
你可以做像@recipes.any?
这样的事来检查你是否得到了一些结果。如果您签入控制器,您可以重定向并使用flash
获取消息,或者您可以在视图中执行此操作并呈现消息。
PS:不是你问,但我真的很想使用ransack来实现复杂的搜索功能。