加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:30:16 所属栏目:百科 来源:网络整理
导读:如何创建具有引用同一个表的两个字段的迁移?我有表A和图像. A.image1_id将引用图像,而A.image2_id也将引用图像.只有2张图片,不多.如果我使用 class AddFields ActiveRecord::Migration def change change_table(:ticket) do |t| t.references :image1_id t.
如何创建具有引用同一个表的两个字段的迁移?我有表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,更详细.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读