CreateJoinTable 迁移 table 命名
CreateJoinTable migration table naming
我有以下迁移:
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
当我 运行 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 table 而不是 questions_tags 吗?
不,这是预期的。
您需要将模型 QuestionTag
重命名为 QuestionsTag
。
This question explain the convention
创建连接的方法有两种table:
- has_and_belongs_to_many:在这种情况下,您的连接 table 具有正确的架构,但您没有它的模型。
- 您有一个连接模型 table 并且您使用
has_many trough:
结构。在这种情况下,您可以简单地 rails g model QuestionTag
并为要连接在一起的模型添加两个 belongs_to
。
我有以下迁移:
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
当我 运行 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 table 而不是 questions_tags 吗?
不,这是预期的。
您需要将模型 QuestionTag
重命名为 QuestionsTag
。
This question explain the convention
创建连接的方法有两种table:
- has_and_belongs_to_many:在这种情况下,您的连接 table 具有正确的架构,但您没有它的模型。
- 您有一个连接模型 table 并且您使用
has_many trough:
结构。在这种情况下,您可以简单地rails g model QuestionTag
并为要连接在一起的模型添加两个belongs_to
。