Sunday, 21 January 2018

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.

No comments:

Post a Comment