我正在使用postgresql全文搜索。我已经成功实现了一切。我只是遇到一个小的if和else语句的小问题。如果没有匹配的查询,我想显示一条消息“找不到结果”。模型,视图和控制器代码分别在下面给出。
Model
include PgSearch
pg_search_scope :search_by_scoreboard,
:against => [:name_of_scoreboard, :name_of_organization, :name_of_activity],
:using => {
:tsearch => {
tsvector_column: "tsv",
:prefix => true,
:dictionary => "english",
:any_word => true
}
}
View
<div id="search">
<%= form_tag search_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search], placeholder: "search scorecliq!" %>
<div id="searchbutton">
<%= submit_tag "Search", :name => nil %>
</div>
<% end %>
<div>
<% if params[:search].present? %>
<% @scoreboard_search.each do |scoreboard_search| %>
<%= div_for scoreboard_search, :class => "inner-disp" do %>
Scoreboard: <%= link_to "#{scoreboard_search.name_of_scoreboard}", scoreboard_path(scoreboard_search.id) %><br>
Organization: <%= scoreboard_search.name_of_organization %><br>
Activity: <%= scoreboard_search.name_of_activity %><br>
state: <%= scoreboard_search.states %><br>
Admin: <%= link_to "#{image_tag scoreboard_search.user.picture}", user_path(scoreboard_search.user.id) %>
picture: <%# image_tag scoreboard_search.user.picture %>
<% end %>
<% end %>
<%= will_paginate @scoreboard_search, :page_links => true %>
<% end %>
controller
def index
@scoreboard_search = Scoreboard.search_by_scoreboard(params[:search]).paginate(:page => params[:page], :per_page => 5)
end
如果是简单查询,我可以在模型中编写if和else语句。但是,我不知道如何使用postgresql全文来做到这一点。我也在控制器中尝试了这个,但它没有用。我试过如果params [:search] .present但那不是正确的方法。这看起来很简单,但我一直在努力解决这个问题。任何帮助将不胜感激,谢谢!!
答案 0 :(得分:2)
您可以在视图中添加条件以检查@scoreboard_search是否包含结果。
<% if params[:search].present? %>
<% if @scoreboard_search.present? %>
<% @scoreboard_search.each do |scoreboard_search| %>
<%= div_for scoreboard_search, :class => "inner-disp" do %>
Scoreboard: <%= link_to "#{scoreboard_search.name_of_scoreboard}", scoreboard_path(scoreboard_search.id) %><br>
Organization: <%= scoreboard_search.name_of_organization %><br>
Activity: <%= scoreboard_search.name_of_activity %><br>
state: <%= scoreboard_search.states %><br>
Admin: <%= link_to "#{image_tag scoreboard_search.user.picture}", user_path(scoreboard_search.user.id) %>
picture: <%# image_tag scoreboard_search.user.picture %>
<% end %>
<% end %>
<%= will_paginate @scoreboard_search, :page_links => true %>
<% else %>
No result found
<% end %>
<% end %>
或检查控制器是否要通过闪存显示消息。 控制器
def index
@scoreboard_search = Scoreboard.search_by_scoreboard(params[:search]).paginate(:page => params[:page], :per_page => 5)
or you can show a flash message
flash[:notice] = "No result found" if @scoreboard_search.nil? || @scoreboard_search.blank?
end