在Rails中使用Sunspot/Solr同时搜索多个模型

3

简单问题,我如何使用Sunspot搜索多个模型?...我正在使用带有Rails的Sunspot,但似乎找不到如何跨多个模型进行搜索。我需要创建一个单独的控制器还是可以使用Gear控制器的索引操作?

感谢您的帮助。

(附注:我在stackoverflow上找到了一个非常类似的问题,但他们没有发布代码..所以对于任何重复请谅解。)

我在我的视图中有以下内容:

<div class="side_bar_search">
    <%= form_tag gears_path, :method => :get do %>
      <p>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
    <% end %>
</div> 

And the following models: 以下是其他型号:
Gear: 齿轮:
class Gear < ActiveRecord::Base
  attr_accessible :title, :size, :price, :sub_category_id, :user_id, :image, :image_a, :remote_image_url
  belongs_to :user
  belongs_to :sub_category
  has_one :category, :through => :sub_category
  has_many :comments, :dependent => :destroy 
  require 'carrierwave/orm/activerecord'
  mount_uploader :image, GearpicUploader
  mount_uploader :image_a, GearpicUploader


  searchable do
    text :title, :size, :price #need to add sub-category, and User Name.  
  end...

用户

class User < ActiveRecord::Base 
  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :userimage, :remove_userimage
  has_secure_password
  has_many :gears
  has_many :comments, :dependent => :destroy 
  has_one :store, :dependent => :destroy
  before_save :create_remember_token
  require 'carrierwave/orm/activerecord'
  mount_uploader :userimage, UserpicUploader

   searchable do
     text :first_name, :last_name
   end...                    

Gears Controller

class GearsController < ApplicationController
  def index
    @search = Gear.search do
        fulltext params[:search]
        paginate(page: params[:page])
    end

    @gears = @search.results
  end...
2个回答

12
Sunspot.search [Gear, User] do
  ....
end

1
不幸的是,如果您正在分页并且Gear中有足够的结果,则不会返回任何User对象。我一直希望它能获取两个结果并按相关性排序。 - Kevin
@Kevin,你能通过按创建日期排序来获取混合的Gear和User列表来解决这个问题吗? - kobaltz
在进行全文搜索时,您可以使用order_by(:score, :desc)按分数对结果进行排序。 - Cristian Bica
这段代码应该放在哪个文件中?我该如何告诉Sunspot进行索引? - Guillermo Siliceo Trueba

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接