CreateJoinTable迁移表命名

时间:2015-01-22 11:09:41

标签: ruby-on-rails ruby-on-rails-4

我有以下迁移:

  

rails g migration CreateJoinTableQuestionTag问号

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

当我运行rake:db:migrate时,它会在 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"

在命令行中:

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

此迁移不应该创建question_tags表而不是questions_tags吗?

2 个答案:

答案 0 :(得分:1)

不,这是预期的。

您需要将模型QuestionTag重命名为QuestionsTag

This question explain the convention

答案 1 :(得分:0)

有两种方法可以创建连接表:

  1. has_and_belongs_to_many:在这种情况下,您的联接表具有正确的架构,但您没有适合它的模型。
  2. 您有一个连接表的模型,并使用has_many trough:构造。在这种情况下,您只需rails g model QuestionTag并为要加入的模型添加两个belongs_to