2012-11-06 110 views
0

我無法找出與此關係的錯誤:HAS_ONE協會工作不

class Education < ActiveRecord::Base 
    attr_accessible :description, :graduation, :student_id, :faculty_id, :department_id 

    has_one :faculty 
    belongs_to :student 
end 
# id   :integer   not null, primary key 
# student_id :integer 
# faculty_id :integer 
# description :text 
# graduation :string(255) 

class Faculty < ActiveRecord::Base 
    attr_accessible :department_id, :name 

    belongs_to :education 
    belongs_to :department 
end 

# == Schema Information 
# 
# Table name: faculties 
# 
# id   :integer   not null, primary key 
# name   :string(255) 
# department_id :integer 

爲什麼我要補充education_idfaculties表? 每個教育只有一個教師和教師屬於許多教育。

>> Education.last.faculty 
    Education Load (0.3ms) SELECT "educations".* FROM "educations" ORDER BY "educations"."id" DESC LIMIT 1 
    Faculty Load (0.2ms) SELECT "faculties".* FROM "faculties" WHERE "faculties"."education_id" = 1 LIMIT 1 
SQLite3::SQLException: no such column: faculties.education_id: SELECT "faculties".* FROM "faculties" WHERE "faculties"."education_id" = 1 LIMIT 1 
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: faculties.education_id: SELECT "faculties".* FROM "faculties" WHERE "faculties"."education_id" = 1 LIMIT 1 
from /Users/rege/.rvm/gems/[email protected]/gems/sqlite3-1.3.6/lib/sqlite3/database.rb:91:in `initialize' 

回答

2

哪一邊你會放一個「belongs_to的」總是有一個關聯對象的ID - 這是根據定義。如果你屬於某個事物,你不屬於另一個事例。

如果希望每個教育只有一個教授,有兩種選擇:

  • 使用一到一個:當你還希望教職工只有一個教育
  • 使用belongs_to的有一個一對多:當你希望每個學院有多個的教育

所以,你可以試試這個:

class Education < ActiveRecord::Base 
    attr_accessible :description, :graduation, :student_id, :faculty_id, :department_id 

    belongs_to :faculty 
    belongs_to :student 
end 

class Faculty < ActiveRecord::Base 
    attr_accessible :department_id, :name 

    has_many :education 
    belongs_to :department 
end 
1

我認爲你們的關係有點亂了 - 在official docs可能會有幫助。

如果我明白你正在嘗試做的,你需要的是這樣的(關於你的教師/教育關係):

class Education < ActiveRecord::Base 
    attr_accessible :description, :graduation, :student_id, :faculty_id, :department_id 

    belongs_to :faculty # foreign key - faculty_id 
    belongs_to :student 
end 
# id   :integer   not null, primary key 
# student_id :integer 
# faculty_id :integer 
# description :text 
# graduation :string(255) 

class Faculty < ActiveRecord::Base 
    attr_accessible :department_id, :name 

    has_many :educations 
    belongs_to :department 
end 
+0

另一個很好的資源是http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to –