gpt4 book ai didi

ruby-on-rails - 在 rails 4 迁移中加入表注释

转载 作者:行者123 更新时间:2023-12-04 13:26:40 24 4
gpt4 key购买 nike

我对 rails 4 还很陌生,我不太确定我的 join_table 应该如何。

我已经完成了迁移

rails g migration CreateJoinTableQuestionSubTopic question sub_topic

我得到这个文件
class CreateJoinTableQuestionSubTopic < ActiveRecord::Migration
def change
create_join_table :questions, :sub_topics do |t|
# t.index [:question_id, :sub_topic_id]
# t.index [:sub_topic_id, :question_id]
end
end
end

为什么这两个索引都在注释中?我以为只有其中一个取消注释,这是正确的方法吗?

有没有必要写
t.column :question_id, :integer
t.column :sub_topic_id, :integer

或/和
t.index :question_id
t.index :sub_topic_id

我想要一个高性能的连接表,但如果 R​​ails 4 上有一个新的连接表,我不想用旧的方式来做

谢谢你的帮助

最佳答案

create_join_table迁移中的命令是 Rails 4 中的新命令。这个:

create_join_table :questions, :sub_topics do |t|
# other commands
end

本质上是这样的简写:
create_table :questions_sub_topics do |t|
t.integer :question_id, null: false
t.integer :sub_topic_id, null: false
# other commands
end

您可以在块中添加其他列;您还可以按照迁移中的注释的建议添加索引。您对索引的选择取决于您打算如何使用这些模型——Rails 不会为您选择,因为它不知道您的意图。如果您经常为给定的问题( question.sub_topics )提取 sub_topics,那么您希望索引首先在 question_id 上,然后是 sub_topic_id:
create_join_table :questions, :sub_topics do |t|
t.index [:question_id, :sub_topic_id]
end

在这种情况下,您不需要仅在 :question_id 上添加索引,因为两列上的索引也用作第一列上的索引。

关于ruby-on-rails - 在 rails 4 迁移中加入表注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724734/

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