Whats missing on my Ruby 'Inverse Of' relationship

I know this topic has been addressed, but I have been at this for 2 days and I'm just stuck. I know inverse of does not create a new query, so should I use another method?

Question: How to set up an 'inverse of' with a has_one, belongs_to situation & same class..

Explanation: A user 'has_one :spouse' and 'belongs_to :spouse_from'. They are inverse of each other. When a User signs up, they can invite their significant other. For Example

  1. user_a invites & creates user_b
  2. user_b.spouse_id is set to user_a.id
  3. In a separate method I want to be able to update like.. user_a.spouse_id = user_a.spouse.id

The only association that works at this point is user_b.spouse.

 Class User
  has_one :spouse, class_name: 'User', foreign_key: :spouse_id, dependent: :nullify, inverse_of: :spouse_from

  belongs_to :spouse_from, class_name: 'User', foreign_key: :spouse_id, inverse_of: :spouse, optional: true

1 answer

  • answered 2022-05-07 12:04 BenFenner

    You need a step 2b in your initial setup to associate a spouse to user_a:

    1a) user_a invites & creates user_b
    2a) user_b.spouse_id is set to user_a.id
    2b) user_a.spouse_id is set to user_b.id (after saving user_b to get an ID for it)
    3a) ...

    This will allow you to later perform the update you wish in another method. The reason that other method update (user_a.spouse_id = user_a.spouse.id) doesn't work right now is because user_a.spouse is nil at the time since that association hasn't been made yet.

    However, and maybe most importantly, that update you describe (user_a.spouse_id = user_a.spouse.id) will never actually accomplish anything, as the right side will always evaluate to the same value that already exists on the left side.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum