在rails 4迁移中加入表注释

Xav*_*avM 6 migration join ruby-on-rails has-and-belongs-to-many ruby-on-rails-4

我在rails 4上很新,我不确定应该如何成为我的join_table.

我完成了迁移

rails g migration CreateJoinTableQuestionSubTopic question sub_topic
Run Code Online (Sandbox Code Playgroud)

我收到这个文件

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
Run Code Online (Sandbox Code Playgroud)

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

没有必要写

t.column :question_id, :integer
t.column :sub_topic_id, :integer
Run Code Online (Sandbox Code Playgroud)

和/或

t.index :question_id
t.index :sub_topic_id
Run Code Online (Sandbox Code Playgroud)

我想有一个高性能的连接表,但如果在rails 4上有一个新表,我不想以旧时尚方式进行

谢谢你的帮助

Wal*_*man 14

create_join_table迁移中的命令是Rails 4中的新命令.

create_join_table :questions, :sub_topics do |t|
  # other commands
end
Run Code Online (Sandbox Code Playgroud)

本质上是简写:

create_table :questions_sub_topics do |t|
  t.integer :question_id,  null: false
  t.integer :sub_topic_id, null: false
  # other commands
end
Run Code Online (Sandbox Code Playgroud)

您可以在块中添加其他列; 您也可以按照迁移中的注释建议添加索引.您选择的索引取决于您打算如何使用这些模型--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
Run Code Online (Sandbox Code Playgroud)

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