Skip to content

Using attachment mapping field in Chewy

nattfodd edited this page Jan 16, 2018 · 2 revisions

Attachment field with Carrierwave uploader column

This example also applicable to a database column that stores the URL of a remote file (e.g. hosted amazon s3 file)

# app/chewy/candidate_index.rb
class CandidateIndex < Chewy::Index
  define_type Candidate.includes({:campaign_invitation => :labels}, :campaign_response_details) do
    field :resume, type: 'attachment', value: -> (candidate) {
      if candidate.resume.present?
        Base64.encode64(open(candidate.resume.url) { |doc| doc.read })
      else
        ""
      end
    }
  end
end

# app/models/candidate.rb
class Candidate < ActiveRecord::Base
  mount_uploader :resume, ResumeUploader

  def self.search(options)
    fields = [ 'resume' ]
    CandidateIndex.query(multi_match: { query: options[:keyword], fields: fields })
  end
end
Clone this wiki locally