0

我有 2 个名为 class1 和 student 的模型,创建它们后,我添加了关联。然后我的模型是:

class Student < ActiveRecord::Base
  attr_accessible :address, :birthdate, :name
  belongs_to :class1
end

class Class1 < ActiveRecord::Base
  attr_accessible :name
  has_many :students
end

我尝试通过 rails 控制台为模型创建实例:

2.0.0-p0 :001 > c=Class1.new(:name=>"A")
 => #<Class1 id: nil, name: "A", created_at: nil, updated_at: nil> 
2.0.0-p0 :002 > c.save
   (0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO `class1s` (`created_at`, `name`, `updated_at`) VALUES ('2013-03-12 08:40:03', 'A', '2013-03-12 08:40:03')
   (40.7ms)  COMMIT
 => true 

但是当我尝试为班级添加学生时,我收到了一个错误:

2.0.0-p0 :003 > s=c.students.build:name=>"Moshe"
ActiveRecord::UnknownAttributeError: unknown attribute: class1_id

列 class_id 确实在数据库中不存在 - 为什么?谢谢!

4

1 回答 1

0

您有责任为该关联添加适当的迁移。

在控制台中:

rails g migration add_class1_references_to_students class1:references

接着:

rake db:migrate
于 2013-03-12T09:00:19.603 回答