Skip to content

Instantly share code, notes, and snippets.

@allomov
Forked from ankane/searchkick_repro.rb
Last active November 5, 2019 08:24
Show Gist options
  • Save allomov/39c30905e94c646fb11637b45f43445d to your computer and use it in GitHub Desktop.
Save allomov/39c30905e94c646fb11637b45f43445d to your computer and use it in GitHub Desktop.
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "activerecord", require: "active_record"
gem "activejob", require: "active_job"
gem "sqlite3"
gem "searchkick", git: "https://github.com/ankane/searchkick.git"
end
puts "Searchkick version: #{Searchkick::VERSION}"
puts "Elasticsearch version: #{Searchkick.server_version}"
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveJob::Base.queue_adapter = :inline
ActiveRecord::Migration.create_table :products do |t|
t.string :name
end
ActiveRecord::Migration.create_table :product_components do |t|
t.string :name
t.float :price
t.integer :product_id
end
class ProductComponent < ActiveRecord::Base
belongs_to :product
end
class Product < ActiveRecord::Base
searchkick
scope :search_import, -> { joins(:product_components).group('products.id').select('products.*, sum(product_components.price) as total_price') }
has_many :product_components
def search_data
{
total_price: total_price
}
end
end
Product.reindex
product = Product.create!(name: "Test")
component1 = ProductComponent.create!(name: "C1", price: 10, product: product)
component2 = ProductComponent.create!(name: "C2", price: 20, product: product)
Product.search_index.refresh
response = Product.search("test").response
# Is it possible to get to `total_price` in response items?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment