cannot load such file — openssl when try to install gem install rails

This is the issue we got when we tried to install rails. In our case, we have an old rails app that runs on the ruby 2.3.1 version, and the rails version is 4.2.6.

On the server where we wanted to install this project had a bit upgraded ruby and rails. But our intention was to use the ruby 2.3.1 version, and the rails version is 4.2.6 for the project.

We were able to downgrade the ruby version easily but when tried to install the rails version 4.2.6 we got into the following error:

$ gem install rails -v 4.2.6
ERROR:  Loading command: install (LoadError)
    cannot load such file -- openssl
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

Reason of the issue

In our case, we had the openssl installed but it needed to recompiled with the downgraded ruby version. The ruby version we added has no openssl and complained about it.

Solution of the issue

If the openssl is not installed then use the following command to install it.

$ rvm pkg install openssl

Once the openssl is installed we need to recompile it with the newly installed (downgraded ruby in our case) ruby version.

$ rvm reinstall ruby-2.3.1  --with-openssl-dir=$rvm_path/usr

Source:
cannot load such file — openssl