0

我需要在我的“教师”模型和“机器人”模型之间建立一对多的关系。每个老师有很多机器人,但每个机器人只有一个老师。

我以为我已经正确设置了它,但是当我尝试在 Rails 控制台中使用它时,输入以下内容:

teacher1.robots = [robot1, robot2]

其中teacher1 是有效的teacher,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

机器人.rb:

class Robot < ActiveRecord::Base
    belongs_to :teacher
end

老师.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

在此先感谢您花时间查看此问题的任何人,如果您对问题所在或如何解决问题有任何想法,将不胜感激。

4

1 回答 1

2

references助手必须与单数模型名称一起使用。您使用了复数形式teachers,导致列名为teachers_id“Active Record 无法找到”。

回滚迁移,将其更改为显示以下内容并重新运行:

t.references 'teacher'
于 2013-07-23T02:05:07.570 回答