使用json / many嵌套活动模型轮胎最佳实践

时间:2013-07-26 14:28:58

标签: ruby-on-rails tire

我想要搜索一个非常复杂的模型层次结构。基本上我有一个人,谁有简历,有很多东西,我想回到与我的自由文本搜索匹配的人(“军队”带来了人民在军队中,寻找“超级棒的师”返回该部门的人员等。

这是我到目前为止(未完成)的一个例子

class Person < ActiveRecord::Base
  has_many :certifications, :as => :certificationable, :dependent => :destroy
  has_many :educations, :as => :educationable, :dependent => :destroy
  has_many :phones, :as => :phoneable, :dependent => :destroy
  has_many :emails, :as => :emailable, :dependent => :destroy
  has_one :resume, :dependent => :destroy
  belongs_to :division
  belongs_to :employment_status
  belongs_to :user

  mapping do

    indexes :id,      index: :not_analyzed
    indexes :first,   analyzer: 'keyword'
    indexes :middle,  analyzer: 'keyword'
    indexes :last,    analyzer: 'keyword'
    indexes :sector
    indexes :job_title
    indexes :div_title
    indexes :loc
    indexes :department
    indexes :unit
    indexes :unit_name, analyzer: 'snowball'

    indexes :division, :analyzer => 'snowball', :class => [Division], :type => :nested

    indexes :employment_status
    indexes :emails do
      indexes :address 
    end

    indexes :phones do
      indexes :number
    end

    indexes :resume do
      indexes :military_services do
        indexes :military_rank do
          indexes :title
          indexes :abbreviation
        end
      end
    end
  end

  def to_indexed_json
    to_json(
        except: [:avatar],
        include: {
          division: {
            only: [:name, :abbrev, :id]
          },

          emails: {
            only: [:address]
          },

          phones: {
            only: [:number]
          },

          resume: {
           include: {
             military_services: {
               exclude: [:updated_at, :created_at],
               include: {
                 military_rank: {
                   only: [:title, :abbreviation]
                 }
               }
             }
           }
          }
        }
    )
  end

  def self.search(params, options = {})
    tire.search(options) do
      query do
        boolean do
          must { string params[:query] } if params[:query].present?
          must { term :division_id, params[:division_id] } if params[:division_id].present?
        end
      end

      sort { by :first, 'asc' }

      facet :division do
        terms :division_id
      end
    end
  end

这似乎有效,但它有点笨拙,因为我必须深入研究索引和json的一些模型。这是实现目标的最佳方式吗?我一直觉得必须有一种方法来索引和映射我的所有模型及其关系,然后将它们与人联系起来。

我也在与json挣扎,因为它非常笨拙。人们会为此使用jbuilder或active_model_serializers吗?

0 个答案:

没有答案