ruby-on-rails – 如何在一个表中添加具有多个引用到同一模型的迁移?的Ruby / Rails

如何创建具有引用同一个表的两个字段的迁移?我有表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到最后,可能不会知道使用’图像’模型.我也想过

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

但那么如何添加其中的两个呢?我也考虑加入

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

但我只想要2,不是很多,这似乎不允许从票据中获取图像,如ticket.image1或ticket.image2.

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

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

解决方法

您可以使用迁移中的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,:foreign_key => "image_2_id"
end

这个博文,Creating Multiple Associations with the Same Table,更详细.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...