Chewy Gem with Active Model Serializers in Ruby on Rails 5.2.3
--
I’ll talk about how to use Chewy gem and Active Model Serializers on Rails app. Chewy is one of ElasticSearch's clients and extends elasticsearch-ruby with various extensions and utilities. It is similar to elasticsearch-rails but I recently had an opportunity to use it in some projects so I’d like to share its usage.
Set up Mysql, ElasticSearch, and Kibana with Docker
To get started with your ElasticSearch app easily, you can use Docker and Docker-compose. I have MySQL 8.0, which is for Ruby on Rails database and ElasticSearch 6.4.2 and Kibana 6.4.2 as below.
Create a docker-compose.yml
in your project folder:
version: '3'
services:
mysql:
image: mysql:8.0
volumes:
- mysqldata:/var/lib/mysql
command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_0900_as_ci --default-authentication-plugin=mysql_native_password
environment:
MYSQL_USER: root
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
elasticsearch:
image: elasticsearch:6.4.2
volumes:
- esdata:/usr/share/elasticsearch/data
environment:
- "ES_JAVA_OPTS=-Xms1g -Xmx1g"
ports:
- "9200:9200"
kibana:
image: kibana:6.4.2
ports:
- "5601:5601"
volumes:
mysqldata:
driver: local
esdata:
driver: local
And start with:
docker-compose up
Now you can access ElasticSearch with http://localhost:9200
and Kibana with http://localhost:5601
.
Set up Ruby on Rails on API mode
To keep the system gem clean, I’m going to create a Ruby on Rails project under my workspace.
Create a Gemfile
first:
$ mkdir my-chewy-app
$ cd my-chewy-app
$ bundle init
Open Gemfile
and uncomment out gem "rails"
:
# frozen_string_literal: true
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
gem "rails"
Install bundles:
bundle install --path vendor/bundle