Answer the question
In order to leave comments, you need to log in
Linking tables across multiple fields?
Hello. There are 2 tables.
Test1 ( id1:integer, id2:integer, id3:integer, enabled:boolean )
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
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
class Test2 < ApplicationRecord
belongs_to :test1, foreign_key: :test2s_id1_id2_id3_fk, class_name: Test1
end
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question