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

前端 未结 2 848
醉酒成梦
醉酒成梦 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

    You can do this simply with the add_column method in your migrations and set up the proper associations in your classes:

    class AddFields < ActiveRecord::Migration
      def change
        add_column :tickets, :image_1_id, :integer
        add_column :tickets, :image_2_id, :integer
      end
    end
    
    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
    

    This blog post, Creating Multiple Associations with the Same Table, goes into more detail.

提交回复
热议问题