如何使用Sunspot / Solr搜索has_many关联?

时间:2013-12-23 20:13:38

标签: ruby-on-rails solr sunspot

以下是我的初始可搜索块在我的用户模型中的样子:

searchable do
  text :name
  integer :sport_ids, multiple: true do
    sports.map(&:id)
  end
  integer :position_ids, multiple: true do
    positions.map(&:id)
  end
  integer :city_id
  integer :school_id
  string :state
end

如何通过has_many关联进行搜索?我需要它来返回每个在运动或sport_positions中具有指定ID的运动员。因此,如果有人从下拉菜单中选择“篮球”,则ID为2会传递给我的搜索方法,并且需要返回sport_id为2的运动员在他们的sport_ids集合中。以下是在用户模型中声明sports和sport_positions的方法:

has_and_belongs_to_many :positions, :class_name => "SportPosition", :join_table => "user_sport_positions", :uniq => true

has_many :sports, :through => :user_sports, order: "user_sports.created_at", class_name: "Sport"

has_many :user_sports

::: EDIT :::

在我重新编制索引后,这工作了一分钟,然后突然间我开始收到此错误:

Sunspot::UnrecognizedFieldError (No field configured for Athlete with name 'sport_ids'):
  app/models/search.rb:12:in `block in execute'

这是我的搜索模型:

class Search < ActiveRecord::Base
  attr_accessible :coach_id, :sport_id, :gpa_min, :gpa_max, :sport_position_id, 
                  :classification, :city_id, :state, :school_id, :athlete_name

  belongs_to :coach

  def self.execute(params, page = nil)
    Sunspot.search(Athlete) do |query|
      query.with :public, true
      query.with :removed_from_listing, false
      query.fulltext params[:athlete_name] unless params[:athlete_name].blank?
      query.with :sport_ids, params[:sport_id] unless params[:sport_id].blank?
      query.with :position_ids, params[:sport_position_id] unless params[:sport_position_id].blank?
      query.with(:state).equal_to(params[:state]) unless params[:state].blank?
      query.with(:classification).equal_to(params[:classification]) unless params[:classification].blank?
      query.with :city_id, params[:city_id] unless params[:city_id].blank?
      query.with :school_id, params[:school_id] unless params[:school_id].blank?
      query.with(:current_gpa).between(params[:gpa_min]..params[:gpa_max]) unless params[:gpa_min].eql?("0.0") && params[:gpa_max].eql?("5.0")
      query.paginate page: page unless page.blank?
    end
  end
end

注意:为了使这更奇怪,我有一个名为“recruit_year”的字段,它是一个整数属性。我在这个字段上得到了同样的错误,说“没有字段配置”等等等等等等。如果您尝试执行equ_to之类的比较或将其视为text,则该错误通常仅发生在string字段上。

帮助?

1 个答案:

答案 0 :(得分:2)

这很好,问题是STI。我有一个覆盖用户区块的运动员区块。