Ch Zeeshan
Ch Zeeshan

Reputation: 1644

Rails belongs_to association is not working

Here is my Course model

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

And Here is my Lesson model

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

I creates a lesson that belongs to a course. lesson created successfully

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

But when i fetch a record of lesson I got course_id=nil. Any Help???

<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">

Upvotes: 0

Views: 2053

Answers (2)

jvnill
jvnill

Reputation: 29599

you need to remove the attr_accessor :course_id line in your model. If you have this line, it creates the following methods in your model which conflicts with what is defined by default

def course_id
  @course_id
end

def course_id=(cid)
  @course_id = cid
end

Upvotes: 2

xdazz
xdazz

Reputation: 160833

Remove attr_accessor :course_id in your Lesson model. This will override the default behavior of the activerecord.

Upvotes: 2

Related Questions