【问题标题】:Join table comment in rails 4 migration在 Rails 4 迁移中加入表注释
【发布时间】:2015-08-23 20:09:11
【问题描述】:

我是 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

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

不用写了吗

t.column :question_id, :integer
t.column :sub_topic_id, :integer

或/和

t.index :question_id
t.index :sub_topic_id

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

感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 join migration has-and-belongs-to-many


    【解决方案1】:

    迁移中的 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
    

    您可以在块中添加其他列;您还可以按照迁移中 cmets 的建议添加索引。您对索引的选择取决于您打算如何使用这些模型——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 上添加索引,因为两列上的索引也用作第一列上的索引。

    【讨论】:

    • 感谢您的回答,我没有找到任何有关此更改的主题。
    猜你喜欢
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2015-06-30
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多