Sunday, 21 January 2018

Publishing Rails 5 apps to heroku

When attempting to migrate the database, I was getting errors with the following two messages

Gem::LoadError: Specified 'postgresql' for database adapter, but the gem is not loaded. Add `gem 'pg'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

Gem::LoadError: can't activate pg (~> 0.18), already activated pg-1.0.0. Make sure all dependencies are added to Gemfile.


The second one turned out to be the main issue.

A solution was found in a rails issue 31669, briefly

Thank you for the issue. Rails still don't support pg 1.0.

My solution was to change the Gemfile reference to

group :production do
gem 'pg', '~> 0.18'
gem 'rails_12factor'
end

And the migration succeeded. Now to apply the issue to the other app I was looking at yesterday...

Rails 5 and optional has_many relationships

This is a continuation in the random notes from attempting to learn Ruby on Rails.

Todays' rambling is to do with having an optional relationship between two tables.
erd from project


I am building an application to help me track fuel usage, and was wanting to have a relationship set between Users and Vehicles, based on the diagram.

The spec tests were failing, because the User:Vehicle relationship was mandatory.

The issue appears to be that Rails 5 has made the belongs_to relationship required (as found in the answer to a StackOverflow question).

The solution seems relatively simple, add the optional link to the relationship:
 
belongs_to :user, optional: true
 
My tests are all passing again. For now.