这是我的课程模式的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">
你在创建'lesson'时是否通过了'course_id'?发布创建'课程'的代码。 – shweta 2013-03-15 12:44:54
是选择下拉菜单中显示的课程我选择课程附加课程,但在课程显示页面课程字段为零 – 2013-03-15 12:53:46
因为'course_id'没有保存。在'Lesson'模型中放置'validates:course_id,:presence => true'行。它不会让任何'课程'创建与'零course_id' – shweta 2013-03-15 13:00:16