如何在一个表中添加对同一模型的多个引用的迁移?的Ruby / Rails

时间:2013-02-14 04:47:40

标签: ruby-on-rails ruby rails-activerecord rails-migrations

如何使用引用同一个表的两个字段创建迁移?我有表A和图像。 A.image1_id将参考图像,而A.image2_id也将参考图像。只有2张图片,而不是很多。如果我使用

class AddFields < ActiveRecord::Migration
   def change
    change_table(:ticket) do |t|
        t.references :image1_id
        t.references :image2_id
    end
  end
end

我认为这不会起作用,因为它会在最后添加另一个_id,并且可能不会知道使用'image'模型。我也想过

change_table(:ticket) do |t|
    t.references :image

但是,我如何添加其中两个呢?我还考虑过添加

create_table :images do |t|
  t.belongs_to :ticket
  t.string :file

但我只想要2,而不是很多,而且这似乎不允许从故障单中获取图像,例如ticket.image1ticket.image2

根据这篇文章http://apidock.com/rails/v3.2.8/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table,这是我能找到的,t.references似乎也没有任何论据。

change_table(:suppliers) do |t|
  t.references :company
end

2 个答案:

答案 0 :(得分:32)

您只需使用迁移中的add_column方法执行此操作,并在类中设置正确的关联:

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

此博客文章Creating Multiple Associations with the Same Table详细介绍。

答案 1 :(得分:6)

在Rails 5.1或更高版本中,您可以这样做:

迁移

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

这将创建字段image1_idimage2_id,并在数据库级别引用images

模型

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

如果您使用FactoryBot,则您的工厂可能看起来像这样:

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