我有一个简单的应用程序,它是用 Rails 5 制作的,我正在使用太阳黑子 solr 进行分面搜索,一切都很好,但分面不起作用,我的代码如下:
模型.rb
searchable do
text :full_name, :interested_topics,:interested_job, :city, :email, :username, :publish_month
text :city
time :created_at
string :publish_month
string :interested_job
end
def publish_month
created_at.strftime("%B %Y")
end
def full_name
first_name + ' ' + last_name
end
控制器.rb
@search = User.search do |searcher|
fields = [:full_name, :interested_topics, :interested_job, :city, :email, :username, :publish_month]
cities = [:city]
searcher.any do
fulltext params[:search], :fields => fields
fulltext params[:city], :fields => cities
end
searcher.with(:created_at).less_than(Time.zone.now)
searcher.with(:publish_month, params[:month]) if params[:month].present?
searcher.with(:interested_job, params[:position]) if params[:position].present?
searcher.paginate(:page => params[:page], :per_page => 15)
end
@users = @search.results
索引.html.erb
<div id="facets">
<%= render partial: "filter" %>
</div>
索引.js.erb
$('#facets').html('<%= escape_javascript(render("filter")) %>');
_filter.html.erb
<h4>Browse by Publish</h4>
<ul class="list-group">
<% for row in @search.facet(:publish_month).rows -%>
<li class="list-group-item">
<input type="checkbox" class="facet-check-box-month" name="month" value="<%= row.value %>" <%= params[:month] == row.value ? "checked" : "" %>>
<%= row.value %>
(<%= row.count %>)
</li>
<% end -%>
</ul>
<h4>Browse by Interest</h4>
<ul class="list-group">
<% for row in @search.facet(:interested_job).rows -%>
<li class="list-group-item">
<input type="checkbox" class="facet-check-box-position" name="position" value="<%= row.value %>" <%= params[:position] == row.value ? "checked" : "" %>>
<%= row.value %>
(<%= row.count %>)
</li>
<% end -%>
</ul>
复选框显示得很好,但是当我单击而不是不查询时。
我做错了什么?
提前谢谢。
您错过了facet
调用,例如在控制器上,您可以将这两行添加到最后一行上方User
块中,例如searcher.paginate(:page => params[:page], :per_page => 15)
searcher.facet(:publish_month)
searcher.facet(:interested_job)
然后重新启动您的sunspot:solr
服务器,我认为它会起作用。
为了更好,在filter
部分使用unless @search.nil?
上,当找不到任何结果时,不会显示复选框,就像修改后一样
<% unless @search.nil? %>
<h4>Browse by Publish</h4>
<ul class="list-group">
<% for row in @search.facet(:publish_month).rows -%>
<li class="list-group-item">
<input type="checkbox" class="facet-check-box-month" name="month" value="<%= row.value %>" <%= params[:month] == row.value ? "checked" : "" %>>
<%= row.value %>
(<%= row.count %>)
</li>
<% end -%>
</ul>
<h4>Browse by Interest</h4>
<ul class="list-group">
<% for row in @search.facet(:interested_job).rows -%>
<li class="list-group-item">
<input type="checkbox" class="facet-check-box-position" name="position" value="<%= row.value %>" <%= params[:position] == row.value ? "checked" : "" %>>
<%= row.value %>
(<%= row.count %>)
</li>
<% end -%>
</ul>
<% end %>
希望对你有帮助