B
B
Bogdan2017-09-24 16:28:15
Ruby on Rails
Bogdan, 2017-09-24 16:28:15

Linking tables across multiple fields?

Hello. There are 2 tables.
Test1 ( id1:integer, id2:integer, id3:integer, enabled:boolean )

Migration for Test1
class CreateTest1s < ActiveRecord::Migration[5.1]
  def change
    create_table :test1s do |t|
      t.integer :id1
      t.integer :id2
      t.integer :id3
      t.boolean :enabled

      t.index [ :id1, :id2, :id3], name: :test1s_id1_id2_id3_un, unique: true
    end

    reversible do |direction|
      direction.up {
        execute <<-SQL.squish
        INSERT INTO test1s ( id1, id2, id3, enabled )
          VALUES
            ( 1, 1, 1, true ),
            ( 1, 1, 2, true ),
            ( 1, 1, 3, true ),
            ( 1, 2, 1, false )
        SQL
      }
    end
  end
end

Test2 ( id1:integer, id2:integer, id3:integer, id4:integer, count:integer )
Migration for Test2
class CreateTest2s < ActiveRecord::Migration[5.1]
  def change
    create_table :test2s do |t|
      t.integer :id1
      t.integer :id2
      t.integer :id3
      t.integer :id4
      t.integer :count
    end

    reversible do |direction|
      direction.up {
        execute <<-SQL.squish
          ALTER TABLE test2s
            ADD CONSTRAINT test2s_id1_id2_id3_fk FOREIGN KEY (id1,id2,id3)
            REFERENCES test1s ( id1,id2,id3 )
        SQL

        execute <<-SQL.squish
          INSERT INTO test2s ( id1, id2, id3, id4, count )
            VALUES
              ( 1, 1, 1, 1, 1 ),
              ( 1, 1, 2, 2, 4 ),
              ( 1, 1, 2, 5, 6 ),
              ( 1, 2, 1, 1, 3 )
          SQL
      }
    end
  end
end

Test2 subordinate Test1 by fields (id1,id2,id3)
How do I properly set up a relationship in the model?
class Test2 < ApplicationRecord
  belongs_to :test1, foreign_key: :test2s_id1_id2_id3_fk, class_name: Test1
end

Googled but didn't google anything. Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question