【发布时间】:2014-01-24 12:53:01
【问题描述】:
我试图在我的 Rails 4.0 项目中理解和设置Sunspot gem。我正在尝试在我的开源项目BTC-Stores 中实现更好的搜索,但我对如何使用 Sunspot 执行此操作有点困惑。
目前,我有以下架构(模型):
项目:
# Relationship with Category
belongs_to :category
accepts_nested_attributes_for :category
searchable do
text :name, :description
integer :category_id
string :sort_name do # why I have this here? I dont understand this code
name.downcase.gsub(/^(an?|the)/, '')
end
end
控制器:
@search = Item.search do
fulltext params[:search] do
boost_fields :name => 2.0
end
# With category
facet :category_id
with(:category_id, params[:category_id]) if params[:category_id].present?
# Kaminari
paginate :page => params[:page], :per_page => 8
end
@items = @search.results
# Here a quick fix to show Category Name, instead of Category ID to user.
@items_categories = []
@search.facet(:category_id).rows.each do |row|
@items_categories << [Category.find_by_id(row.value), row.count]
end
@items_categories = @items_categories.sort_by { |e| e[0].name }
查看:
<% @items_categories.each do |category| %>
<div class="country-item">
<a href="#" class="country-row">
<div class="country">
<% if params[:category_id].blank? %>
<%= link_to category[0].name, :category_id => category[0].id %> (<%= category[1] %>)
<% else %>
<%= category[0].name %>(<%= link_to "remove", :category_id => nil %>)
<% end %>
</div>
</a>
</div>
<% end %>
问题:
当我搜索某些内容时,我会得到想要的结果。看一下分类,主要看网址:
现在,如果我单击任何列出的类别,而不是将类别添加到“获取”参数,这是删除旧参数,然后添加 category_id 参数。
现在我的网址是http://localhost:3000/stores?category_id=6,而不是http://localhost:3000/stores?utf8=%E2%9C%93&search=bitcoin&category_id=6。看:
那么,我做错了什么?还有一件事,如果您在我的代码中发现问题以及可以做得更好的事情,请告诉我。我阅读了所有Sunspot documentation 和RailsCast by Ryan Bates,但我不明白如何以“正确的方式”做事。
【问题讨论】:
标签: ruby-on-rails solr sunspot