0

年齢層で絞り込み検索したい。

今私は持っています: program.rb

class Program < ActiveRecord::Base
  has_many :age_groups, through: :programs_age_groups_relations
  include Tire::Model::Search
  include Tire::Model::Callbacks
  mapping do
    indexes :name, analyzer: 'snowball', boost: 100
    indexes :description, analyzer: 'snowball'
    indexes :age_groups do
      indexes :name, analyzer: 'snowball'
    end
  end

  def to_indexed_json
    to_json(include: {age_groups: {only: :name}})
  end
  def self.search(params, options={})
    tire.search(load: {include: 'age_groups'}) do
      query do
        boolean do
          must { string params[:name_query] } if params[:name_query].present?
        end
      end

    filter do
      boolean do
        if params[:age_groups].present?
          params[:age_groups].each do |ag_name|
            must { string ag_name }
          end
        end
      end
    end
  end
end

index.html.haml

= form_tag programs_path, method: :get do |f|
  = text_field_tag :name_query, params[:name_query]
  - AgeGroup.all.each do |ag|
    = check_box_tag 'age_groups[]', ag.name, params[:age_groups].include?(ag.name)

コントローラーで:

@programs = Program.search(params)

年齢グループ:

AgeGroup.create([{name: 'Baby'}, {name: 'Toddler'}, {name: 'Preschoolers'}, {name: 'Elementary'}, {name: 'Middle School'}])

関係:

class ProgramsAgeGroupsRelation < ActiveRecord::Base
  attr_accessible :age_group_id, :program_id
  belongs_to :age_group
  belongs_to :program
end

検索フォームで 1 つ以上の age_groups をチェックしても、検索結果に何も起こりませんでした。

このタスクでタイヤを正しく使用するにはどうすればよいですか?

4

1 に答える 1

2

あなたの質問を理解できるかどうかわかりませんが、この StackOverflow の回答を確認してください: ActiveRecord との関連付けに関する情報については、Elasticsearch、Tire、および ActiveRecord とのネストされたクエリ/関連付けです。

「検索結果で何も起こらなかった」というのは、ある種の失敗した期待を示唆しているので、それを整理したら、質問を更新してください。

于 2012-08-06T14:10:10.680 に答える