簡體   English   中英

在StudentController#destroy中的ActiveRecord :: StatementInvalid找不到表'students_subjects'

[英]ActiveRecord::StatementInvalid in StudentsController#destroy Could not find table 'students_subjects'

我有以下兩個控制器

class Student < ActiveRecord::Base
  has_and_belongs_to_many :subjects
end

class Subject < ActiveRecord::Base
  has_and_belongs_to_many :semesters
  has_and_belongs_to_many :students
end

我的數據庫表是

class CreateSubjects < ActiveRecord::Migration
  def self.up
    create_table :subjects do |t|
      t.string :name

      t.timestamps
    end
  end

  def self.down
    drop_table :subjects
  end
end

class CreateStudents < ActiveRecord::Migration
  def self.up
    create_table :students do |t|
      t.string :name
      t.string :dept

      t.timestamps
    end
  end

  def self.down
    drop_table :students
  end
end

我對主題和學生作品的編輯,顯示,創建都很好。 但是,當我嘗試刪除任何學科或學生時,出現以下錯誤

ActiveRecord :: StatementInvalids在SubjectsController#destroy中

找不到表格“ students_subjects”

似乎應該有一個名為“ students_subjects”的表,用於多對多關聯。 我怎么做? 使用腳手架之類的東西? 我剛剛開始學習Rails。

該錯誤表明您缺少has_and_belongs_to_many關聯中的has_and_belongs_to_many表。 studentsubject editshowcreate只能分開進行。 由於缺少聯接表,因此在數據庫中沒有創建任何關聯的記錄。

創建一個遷移以添加聯接表。 請注意,此聯接表不需要模型。

class CreateStudentsSubjects < ActiveRecord::Migration
  def self.up
    create_table :students_subjects, id: false do |t|
      t.references :student, null: false
      t.references :subject, null: false
    end

    # Add an unique index for better join speed!
    add_index(:students_subjects, [:student_id, :subject_id], :unique => true)
  end

  def self.down
    drop_table :students_subjects
  end
end

更新:

如何創建遷移?

從Rails應用程序的根目錄發出以下命令:

rails g migration create_students_subjects

然后,使用上面的類定義替換db/migrate/目錄中生成的遷移文件的內容。 然后執行rake db:migrate

請注意,我在上面的create_table方法中錯過了id: false來告訴Rails不要為此表創建主鍵。 我在此更新中添加了此選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM