如何在一个表中添加对同一模型的多个引用的迁移?红宝石/轨道 [英] How do I add migration with multiple references to the same model in one table? Ruby/Rails

查看:37
本文介绍了如何在一个表中添加对同一模型的多个引用的迁移?红宝石/轨道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 also. There are only 2 images, not many. If I use

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

我认为这行不通,因为它会在末尾添加另一个 _id 并且可能不知道使用图像"模型.我也想过

I don't think that will work because it will add another _id to the end and probably won't know to use the 'image' model. I also thought about

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

但是我该如何添加其中的两个呢?我也想过加

But then how do I add two of those? I also thought about adding

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

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

But I only want 2, not many, and this doesn't appear to allow getting to the image from the ticket, like ticket.image1 or ticket.image2.

根据本文档http://apidock.com/rails/v3.2.8/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table 这是我能找到的全部,t.references 似乎也没有任何参数.

According to this documentation http://apidock.com/rails/v3.2.8/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table which is all I could find, t.references doesn't appear to take any arguments either.

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

推荐答案

您可以在迁移中使用 add_column 方法简单地做到这一点,并在您的类中设置适当的关联:

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

这篇博文,创建多个相同的关联表,更详细.

这篇关于如何在一个表中添加对同一模型的多个引用的迁移?红宝石/轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆