0

I have the following migration:

rails g migration CreateJoinTableQuestionTag question tag

class CreateJoinTableQuestionTag < ActiveRecord::Migration
  def change
    create_join_table :questions, :tags do |t|
      t.index [:question_id, :tag_id]
      t.index [:tag_id, :question_id]
    end
  end
end

When i run rake:db:migrate it creates this in schema.rb:

  create_table "questions_tags", id: false, force: :cascade do |t|
    t.integer "question_id", null: false
    t.integer "tag_id",      null: false
  end

  add_index "questions_tags", ["question_id", "tag_id"], name: "index_questions_tags_on_question_id_and_tag_id"
  add_index "questions_tags", ["tag_id", "question_id"], name: "index_questions_tags_on_tag_id_and_question_id"

In the comand line:

QuestionTag.first
  QuestionTag Load (0.9ms)  SELECT  "question_tags".* FROM "question_tags"  ORDER BY "question_tags"."id" ASC LIMIT 1
SQLite3::SQLException: no such table: question_tags: SELECT  "question_tags".* FROM "question_tags"  ORDER BY "question_tags"."id" ASC LIMIT 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: question_tags: SELECT

Shouldn't this migration create a question_tags table instead of questions_tags?

Barna Kovacs
  • 1,226
  • 1
  • 14
  • 35

2 Answers2

1

No, this is the expected.

You'll need to rename your model QuestionTag to QuestionsTag.

This question explain the convention

Community
  • 1
  • 1
Rodrigo
  • 5,435
  • 5
  • 42
  • 78
0

There are two ways to create a join table:

  1. has_and_belongs_to_many: in this case your join table has the right schema, but you don't have a model for it.
  2. you have a model for your join table and you use the has_many trough: construct. In this case you can simply rails g model QuestionTag and add the two belongs_to for the models you want to join together.
tmichel
  • 954
  • 7
  • 7