0

I am building a Ruby on Rails 6 application where I have a model Archive, and a another model ArchiveAgencies. In the Archive model I must have a sender agency and a receiver agency, which should represent ArchiveAgencies.

After going through the Rails docs, and some StackOverflow QA:

I came up with this approach:

Models

class Archive < ActiveRecord::Base
  belongs_to :sender_agency, class_name: ArchiveAgencies, foreign_key: "sender_agency_id"
  belongs_to :receiver_agency, class_name: ArchiveAgencies, foreign_key: "receiver_agency_id"
end
class ArchiveAgency < ActiveRecord::Base
  has_many :archives, inverse_of: 'sender_agency'
  has_many :archives, inverse_of: 'receiver_agency'
end

Migration

class CreateArchiveAgencies < ActiveRecord::Migration[6.0]
  def change
    create_table :archives do |t|
      t.string :name

      t.timestamps
    end
  end
end
class CreateArchives < ActiveRecord::Migration[6.0]
  def change
    create_table :archives do |t|
      t.references :sender_agency, foreign_key: { to_table: :archive_agencies }
      t.references :receiver_agency, foreign_key: { to_table: :archive_agencies }

      t.timestamps
    end
  end
end

Is this the best approach for this case? Would, having two inverse_of statements in the model ArchiveAgency work?

1 Answers1

1

If you declare multiple associations with the same name the last one will overwrite the others.

Instead you need to use unique names for each association and configure them properly:

class ArchiveAgency < ActiveRecord::Base
  has_many :archives_as_sender, 
     inverse_of: :sender_agency,
     foreign_key: :sender_agency_id,
     class_name: 'Archive'

  has_many :archives_as_receiver, 
     inverse_of: :receiver_agency,
     foreign_key: :receiver_agency_id,
     class_name: 'Archive'
end

class Archive < ActiveRecord::Base
  belongs_to :sender_agency, # foreign_key can be derived from the name
     class_name: 'ArchiveAgency', # needs to be a string - not the class itself
     inverse_of: :archives_as_sender 
  belongs_to :receiver_agency, 
     class_name: 'ArchiveAgency'
     inverse_of: :archives_as_receiver
end
max
  • 96,212
  • 14
  • 104
  • 165