2013-07-23 56 views
0

我需要在我的「老師」模型和我的「機器人」模型之間建立一對多的關係。每個老師都有很多機器人,但每個機器人只有一名老師。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 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 

謝謝你在前進的人誰花時間看通過這一點,任何想法是什麼問題或如何解決它將不勝感激。

+0

你實際運行遷移? '耙db:migrate' – Substantial

+0

是的,我跑了兩次,並確保沒有變化發生第二次我跑它 – Dsel

回答

2

references幫手必須使用單數型號名稱。您使用複數teachers,導致Active Record無法找到名爲teachers_id的列。

回滾遷移,改變它顯示以下內容並重新運行:

t.references 'teacher'