How do I add migration with multiple references to the same model in one table? Ruby/Rails

前端 未结 2 851
醉酒成梦
醉酒成梦 2020-12-08 14:35

How do I create a migration with two fields that reference the same table? I have tables A, and image. A.image1_id will reference image, and A.image2_id will reference image

2条回答
  •  孤城傲影
    2020-12-08 14:58

    In Rails 5.1 or greater you can do it like this:

    Migration

    class AddFields < ActiveRecord::Migration
       def change
        change_table(:tickets) do |t|
            t.references :image1, foreign_key: { to_table: 'images' }
            t.references :image2, foreign_key: { to_table: 'images' }
        end
      end
    end
    

    This will create the fields image1_id, and image2_id and make the database level references to the images table

    Models

    as in rossta's asnwer

    class Ticket < ActiveRecord::Base
      belongs_to :image_1, class_name: "Image"
      belongs_to :image_2, class_name: "Image"
    end
    
    class Image < ActiveRecord::Base
      has_many :primary_tickets, class_name: "Ticket", foreign_key: "image_1_id"
      has_many :secondary_tickets, class_name: "Ticket", foreign_key: "image_2_id"
    end
    

    FactoryBot

    If you uses FactoryBot then your factory might look something like this:

    FactoryBot.define do
      factory :ticket do
        association :image1, factory: :image
        association :image2, factory: :image
      end
    end
    

提交回复
热议问题