如何创建引用同一表的两个字段的迁移?我有表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
发布于 2013-02-14 13:18:27
您只需在迁移中使用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的博客文章详细介绍了这一点。
发布于 2019-08-02 16:02:58
在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_id
和image2_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
https://stackoverflow.com/questions/14867981
复制相似问题