Join table comment in rails 4 migration

811 views Asked by At

I'm pretty new on rails 4 and I'm not really sure about how should be my join_table.

I've done the migration

rails g migration CreateJoinTableQuestionSubTopic question sub_topic

And I get this file

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

Why the two indexes are in comments ? I thought uncomment only one among these, is it the right way ?

Is there no need to write

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

Or/And

t.index :question_id
t.index :sub_topic_id

I would like to have a performant join table but I do not want to do it on old fashion way if there is a new one on rails 4

Thanks for your help

1

There are 1 answers

1
Wally Altman On BEST ANSWER

The create_join_table command in migrations is new in Rails 4. This:

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

is essentially shorthand for this:

create_table :questions_sub_topics do |t|
  t.integer :question_id,  null: false
  t.integer :sub_topic_id, null: false
  # other commands
end

You can add additional columns in the block; you could also add indexes, as suggested by the comments in the migration. Your choice of indexes depends on how you intend to use these models—Rails doesn't choose for you because it doesn't know what you intend. If you will often be pulling up the sub_topics for a given question (question.sub_topics), then you want your index to be first on question_id, then sub_topic_id:

create_join_table :questions, :sub_topics do |t|
  t.index [:question_id, :sub_topic_id]
end

In this case, you don't need to add an index just on :question_id, as the index on two columns also serves as an index on the first column.