title: Creating a belongs_to relationship with a multiple field index instead of primary key
body: <h2>Context</h2>
  <p>Imagine the following: I have a model <code>Sector</code> that contains an ID as primary key (which I want to keep) and that model has two attributes that are unique together and with an index about their location (ie. Sectors cannot be in the same position).</p>
  <pre><code># Table name: sector
  #
  #  id      :bigint           not null, primary key
  #  x       :bigint           not null
  #  y       :bigint           not null
  #  attrA   :datetime
  #  attrB   :boolean
  #  attrC   :string
  #  (etc)
  #
  # Indexes
  #
  #  sector_index         (x,y) UNIQUE
  </code></pre>
  <p>Now, let's imagine that we have objects that are at a specific location, and that location may change (objects move around).</p>
  <pre><code># Table name: object
  #
  #  id  :bigint           not null, primary key
  #  x   :bigint           not null
  #  y   :bigint           not null
  </code></pre>
  <h2>Problem</h2>
  <p><strong>How to join these tables efficiently??</strong></p>
  <h2>Option 1 - ID as foreign key</h2>
  <p>The obvious off the shelf solution to join these two tables is to create a <code>belongs_to :sector</code>, which would need a <code>sector_id</code> foreign key. However, every time we need to update a large number of objects' positions, we would need to query the sector table to get the ID of the sector containing X and Y. (eg, let's say we need to move all objects 3 sections in the Y direction)</p>
  <h2>Option 2: Ditching the <code>belongs_to</code> and use a model attribute</h2>
  <p>The other choice is to have</p>
  <pre><code>class Object &lt; ApplicationRecord
    def sector
      Sector.where(x: x, y:y)
    end
  end
  </code></pre>
  <p>The obvious disadvantage is that this does not allow any preloading or table joins, and will result in n+1</p>
  <h2>Option 3 - using Gem composite primary key</h2>
  <p>The gem Composite primary keys - <a href="https://github.com/composite-primary-keys/composite_primary_keys" rel="nofollow noreferrer">https://github.com/composite-primary-keys/composite_primary_keys</a> - allows the use composite primary keys, but I would like to keep the ID as a primary key.</p>
  <h2>Question</h2>
  <p>Can we somehow use the unique index to create a belongs_to association that can take advantage of the Rails ActiveRecord helpers and methods such as <code>includes</code> and <code>preloads</code> and <code>joins</code>? Maybe create additional (non primary) composite key in the Sector?</p>
  <h2>Other references I found:</h2>
  <p>Shopify composite primary keys - <a href="https://shopify.engineering/how-to-introduce-composite-primary-keys-in-rails" rel="nofollow noreferrer">https://shopify.engineering/how-to-introduce-composite-primary-keys-in-rails</a></p>