Nei*_*eil 52 ruby-on-rails rails-migrations
我有以下两种型号:
class Store < ActiveRecord::Base
belongs_to :person
end
class Person < ActiveRecord::Base
has_one :store
end
Run Code Online (Sandbox Code Playgroud)
这是问题所在:我正在尝试创建迁移以在people表中创建外键.但是,引用Store外键的列未命名为store_id,因为它是rails约定,而是命名为foo_bar_store_id.
如果我遵循rails约定,我会像这样进行迁移:
class AddReferencesToPeople < ActiveRecord::Migration
def change
add_reference :people, :store, index: true
end
end
Run Code Online (Sandbox Code Playgroud)
但是这不起作用,因为列名不是store_id,而是foo_bar_store_id.那么我如何指定外键名称只是不同,但仍保持索引:true以保持快速性能?
sch*_*pet 69
在rails 5.x中,您可以将外键添加到具有不同名称的表中,如下所示:
class AddFooBarStoreToPeople < ActiveRecord::Migration[5.0]
def change
add_reference :people, :foo_bar_store, foreign_key: { to_table: :stores }
end
end
Run Code Online (Sandbox Code Playgroud)
Sia*_*Sia 66
在Rails 4.2中,您还可以使用自定义外键名称设置模型或迁移.在您的示例中,迁移将是:
class AddReferencesToPeople < ActiveRecord::Migration
def change
add_column :people, :foo_bar_store_id, :integer, index: true
add_foreign_key :people, :stores, column: :foo_bar_store_id
end
end
Run Code Online (Sandbox Code Playgroud)
这是一篇关于这个主题的有趣博客文章.这是Rails指南中的半隐藏部分.这篇博文绝对帮助了我.
对于关联,显式地声明这样的外键或类名(我认为你的原始关联被切换为'belongs_to'在具有外键的类中):
class Store < ActiveRecord::Base
has_one :person, foreign_key: :foo_bar_store_id
end
class Person < ActiveRecord::Base
belongs_to :foo_bar_store, class_name: 'Store'
end
Run Code Online (Sandbox Code Playgroud)
请注意,class_name项必须是字符串.foreign_key项可以是字符串或符号.这实际上允许您使用语义命名的关联访问漂亮的ActiveRecord快捷方式,如下所示:
person = Person.first
person.foo_bar_store
# returns the instance of store equal to person's foo_bar_store_id
Run Code Online (Sandbox Code Playgroud)
有关belongs_to和has_one文档中的关联选项的更多信息,请参阅.
编辑:对于那些看到滴答声,不要继续阅读!
尽管此答案实现了使用索引建立具有非常规外键列名称的目标,但并未向数据库添加fk约束。请参阅其他答案,以使用add_foreign_key
和/或'add_reference' 更合适的解决方案。
注意:总是看看其他答案,公认的答案并不总是最好的!
原始答案:
在AddReferencesToPeople
迁移中,您可以使用以下方法手动添加字段和索引:
add_column :people, :foo_bar_store_id, :integer
add_index :people, :foo_bar_store_id
Run Code Online (Sandbox Code Playgroud)
然后让您的模型知道外键,如下所示:
class Person < ActiveRecord::Base
has_one :store, foreign_key: 'foo_bar_store_id'
end
Run Code Online (Sandbox Code Playgroud)
# Migration
change_table :people do |t|
t.references :foo_bar_store, references: :store #-> foo_bar_store_id
end
# Model
# app/models/person.rb
class Person < ActiveRecord::Base
has_one :foo_bar_store, class_name: "Store"
end
Run Code Online (Sandbox Code Playgroud)
为了扩展schpet的答案,它可以在create_table
Rails 5迁移指令中工作,如下所示:
create_table :chapter do |t|
t.references :novel, foreign_key: {to_table: :books}
t.timestamps
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
38449 次 |
最近记录: |