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

StackOverflow https://stackoverflow.com/questions/20851783

Вопрос

I have following two controller

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

And my database tables are

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

My edit, show, create of subject and student work just fine. But when I try to delete any subject or student I get the following error

ActiveRecord::StatementInvalid in SubjectsController#destroy

Could not find table 'students_subjects'

It seems there should be another table named 'students_subjects' for many to many association. How do I do that? Using scaffold or something? I just started to learn rails.

Это было полезно?

Решение

The error is saying that you are missing the join table in the has_and_belongs_to_many association. Your edit, show, create of student and subject should only work separately. There are no associated records created in the database because the join table is missing.

Create a migration to add the join table. Note that you wouldn't need a model for this join table.

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

Update:

How to create a migration?

Issue the following command from your rails application root directory:

rails g migration create_students_subjects

Then replace the content of the generated migration file in db/migrate/ directory with the class definition above. Then after execute rake db:migrate.

Note that I had missed id: false in the create_table method above to tell Rails not to create a primary key for this table. I've added this option with this update.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top