gpt4 book ai didi

ruby-on-rails - Rails 迁移 : add_reference to Table but Different Column Name For Foreign Key Than Rails Convention

转载 作者:行者123 更新时间:2023-12-03 05:50:53 25 4
gpt4 key购买 nike

我有以下两个模型:

class Store < ActiveRecord::Base
belongs_to :person
end

class Person < ActiveRecord::Base
has_one :store
end

问题是:我正在尝试创建迁移以在 people 表中创建外键。但是,引用 Store 外键的列并未按照 Rails 约定命名为 store_id,而是命名为 foo_bar_store_id

如果我遵循 Rails 约定,我会像这样进行迁移:

class AddReferencesToPeople < ActiveRecord::Migration
def change
add_reference :people, :store, index: true
end
end

但是,这不起作用,因为列名称不是 store_id,而是 foo_bar_store_id。那么如何指定外键名称只是不同,但仍保持 index: true 以保持快速性能?

最佳答案

在 Rails 5.x 中,您可以向具有不同名称的表添加外键,如下所示:

class AddFooBarStoreToPeople < ActiveRecord::Migration[5.0]
def change
add_reference :people, :foo_bar_store, foreign_key: { to_table: :stores }
end
end

create_table block 内

t.references :feature, foreign_key: {to_table: :product_features}

关于ruby-on-rails - Rails 迁移 : add_reference to Table but Different Column Name For Foreign Key Than Rails Convention,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com