Version Association

Hi,

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)
end

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:

https://github.com/lorint/brick/assets/5301131/9f73e28b-66a1-4c03-8c67-064158890e59

All the best,

-Lorin

Hi,

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!