[英]Rails, one-to-many relationship error in rails console
我需要在我的“老师”模型和我的“机器人”模型之间建立一对多的关系。 每位老师都有很多机器人,但每个机器人只有一位老师。
我以为我已经正确设置但是当我尝试在rails控制台中使用它时输入以下内容:
teacher1.robots = [robot1, robot2]
其中teacher1是有效的教师,robot1和robot2都是有效的机器人,产生此错误:
SQLite3::SQLException: no such column: robots.teacher_id: SELECT "robots".* FROM "robots" WHERE "robots"."teacher_id" = 14
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: robots.teacher_id: SELECT "robots".* FROM "robots" WHERE "robots"."teacher_id" = 14
我是Ruby(以及Ruby on Rails)的新手,但在我完成的所有研究中,我发现我的模型或迁移方式都没有发现任何错误......以下是两个模型文件和迁移。
* _create_robots.rb:
class CreateRobots < ActiveRecord::Migration
def up
create_table 'robots' do |t|
t.text 'serial'
t.references 'teachers'
end
end
def down ; drop_table 'robots' ; end
end
robot.rb:
class Robot < ActiveRecord::Base
belongs_to :teacher
end
teacher.rb:
class Teacher < ActiveRecord::Base
has_many :robots
before_destroy :confirm_no_inventory
protected
def confirm_no_inventory
unless self.usb_cords == 0 and self.simple_snaps == 0 and self.casters == 0
errors.add(:base, "All checked out items must be returned before #{self.name} can be deleted")
return false
end
end
end
提前感谢任何花时间仔细研究这个问题的人,对问题是什么或如何修复它的任何想法都将非常感激。
references
帮助程序必须与单个模型名称一起使用。 您使用复数teachers
导致一个名为teachers_id
的列,Active Record无法找到该列。
回滚迁移,更改它以显示以下内容并重新运行:
t.references 'teacher'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.