【问题标题】:Rails migration for has_and_belongs_to_manyhas_and_belongs_to_many 的 Rails 迁移
【发布时间】:2020-10-28 02:24:08
【问题描述】:

这是在驱使我 BANANAS。我已经尝试了多种迁移方式,但这种关系似乎只有一种方式。我想要一个可以Event.first.subjects << Subject.firstEvent.last.subjects << Subject.first的关系

class Event < ApplicationRecord
    has_and_belongs_to_many :subjects 
end

class Subject < ApplicationRecord
    has_and_belongs_to_many :events
end

我创建了一个迁移

rails g migration CreateJoinTableEventSubject events subjects
class CreateJoinTableEventSubject < ActiveRecord::Migration[5.2]
  def change
    create_join_table :events, :subjects do |t|
      t.index [:event_id, :subject_id]
      t.index [:subject_id, :event_id]
    end
  end
end

我可以Subject.first.events 我不需要但Event.first.subjects 返回

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: subjects.event_id: SELECT  "subjects".* FROM "subjects" WHERE "subjects"."event_id" = ? LIMIT ?)

这里是schema.rb

ActiveRecord::Schema.define(version: 2020_07_07_183602) do

  create_table "events", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.date "date"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "events_subjects", id: false, force: :cascade do |t|
    t.integer "event_id", null: false
    t.integer "subject_id", null: false
    t.index ["event_id", "subject_id"], name: "index_events_subjects_on_event_id_and_subject_id"
    t.index ["subject_id", "event_id"], name: "index_events_subjects_on_subject_id_and_event_id"
  end

  create_table "subjects", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

【问题讨论】:

  • 你运行迁移了吗?尝试重新启动服务器..
  • 粘贴到这里或查看 schema.rb
  • 是的,跑了rails db:migrate。这是在控制台中,但我尝试了一个新的控制台并重新启动了服务器。
  • 从您共享的所有内容中,它应该可以工作,如您所知。我怀疑您忘记删除 Subject 模型中的 belongs_to :event 行,或者您共享的信息中未反映的其他错字。

标签: ruby-on-rails ruby-on-rails-5 database-migration


【解决方案1】:

所以我一直在通过删除 development.sqlite3 文件来清除数据库。当我为此实际运行rails db:drop 并运行迁移时,它开始工作。我猜有一些工件在没有实际删除数据库的情况下被保留了下来?

感谢评论者让我想到这一点。

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 2014-02-28
    • 2011-05-21
    • 2016-05-28
    • 1970-01-01
    • 2011-12-02
    • 2012-01-14
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多