【问题标题】:How to search in has_many association using Sunspot/Solr?如何使用 Sunspot/Solr 在 has_many 关联中搜索?
【发布时间】:2013-12-23 20:13:38
【问题描述】:

这是我最初的可搜索块在我的用户模型中的样子:

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 关联进行搜索?我需要它来返回在他们的运动或运动位置中具有指定 ID 的每个运动员。因此,如果有人从下拉列表中选择“篮球”,则 ID 为 2 将传递给我的搜索方法,并且它需要返回在他们的 sport_id 集合中的 sport_id 为 2 的运动员。以下是在 User 模型中声明 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”的字段,它是一个整数属性。我在这个字段上遇到了同样的错误,说“没有配置字段”等等。如果您尝试进行类似 equal_to 的比较或将其视为 string,则该错误通常仅发生在 text 字段上。

帮助?

【问题讨论】:

    标签: ruby-on-rails solr sunspot


    【解决方案1】:

    这工作正常,问题是 STI。我有一个覆盖用户块的运动员块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多