Version Association


I have data in my Car model like so:

id, name, original_version_id
76494, FA, 76494
77303, KH, 76494

I have these associations in my Versionable Concern:

belongs_to :original_version, class_name: self.to_s, optional: true
has_many :versions, class_name: self.to_s, foreign_key: 'original_version_id'

In the console, If I do:

fa = Car.find(76494)
kh = Car.find(77303)

and then

fa.versions.count # Returns 2
kh.versions.count # Returns 0

Any ideas why? I want both records to get returned when I call .versions on either of them.

I’m really confused here.

Heya Neil – what you need to do is remove the has_many and add this method:

def versions
  Car.where(original_version_id: self.original_version_id)

In this way when you ask for kh.versions it will try to find all other cars which have the same original_version that it does.

Here’s a video peek to describe it a bit more, with a deeper look into self-referencing JOINs:

All the best,



Lorin, that’s super helpful! Thankyou so much for the video! I will be sure to take a look into your Brick gem to help see the organisation of my data.

Switching this from a has_many to just a method definitely solves the problem!

Thanks again!