2013-03-15 77 views
0

這是我的課程模式的Rails belongs_to的關聯沒有工作

class Course < ActiveRecord::Base 
    attr_accessible :longdescription, :shortdescription, :title, :published_at 
    has_many :lessons, :foreign_key => 'course_id' 
end 

,這裏是我的課程模式

class Lesson < ActiveRecord::Base 
    belongs_to :course, :class_name => 'Course' 
    attr_accessor :course_id 
    attr_accessible :description, :title, :course_id 
end 

我創建了屬於一門課程一節課。教程創建成功

Lesson.create(:title => "testing", :description => "causing problems", :course_id => 1) 

但是,當我獲取教訓的記錄,我得到了course_id = nil。任何幫助?

<Lesson id: 8, title: "testing", description: "causing problems", course_id: nil, created_at: "2013-03-15 12:56:36", updated_at: "2013-03-15 12:56:36"> 
+0

你在創建'lesson'時是否通過了'course_id'?發佈創建'課程'的代碼。 – shweta 2013-03-15 12:44:54

+0

是選擇下拉菜單中顯示的課程我選擇課程附加課程,但在課程顯示頁面課程字段爲零 – 2013-03-15 12:53:46

+0

因爲'course_id'沒有保存。在'Lesson'模型中放置'validates:course_id,:presence => true'行。它不會讓任何'課程'創建與'零course_id' – shweta 2013-03-15 13:00:16

回答

2

您需要刪除模型中的attr_accessor :course_id行。如果你有這條線,它將在你的模型中創建以下與默認定義內容相沖突的方法

def course_id 
    @course_id 
end 

def course_id=(cid) 
    @course_id = cid 
end 
+0

如果我刪除該行,我得到這個錯誤「ActiveModel :: MassAssignmentSecurity ::錯誤:無法批量分配受保護的屬性:courses_id」 – 2013-03-15 13:17:55

+2

你傳遞'courses_id'而不是'course_id'。檢查你的代碼。 – jvnill 2013-03-15 13:19:26

+0

我糾正錯誤課程的錯誤,但原始問題在那裏,因爲它是 – 2013-03-15 13:25:23

2

刪除attr_accessor :course_id在您的Lesson模型。這將覆蓋activerecord的默認行爲。

+0

如果我刪除該行,我得到這個錯誤「ActiveModel :: MassAssignmentSecurity ::錯誤:無法批量分配受保護的屬性:courses_id「 – 2013-03-15 13:18:14

+0

你真正想要的是'attr_accessible:course_id'。 – thomasfedb 2013-03-15 16:47:46