Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many and belongs_to relationship with foreign key error

I am trying to implement a has_many and belongs_to relationship on rails with a foreign key but I face trouble trying to implement it correctly, any help would be appreciated. I am using this as a guide as well: http://guides.rubyonrails.org/association_basics.html

The two models are subject and lessons. A subject has many lessons and a lesson belongs to a subject. The foreign key is subject_code.

The following is the relevant codes.

Subject Model

class Subject < ActiveRecord::Base
                  :subject_code, 
                  :subject_name
                  :lessons_attributes

  has_many :lessons,
           :foreign_key => "subject_code"

  accepts_nested_attributes_for :lessons, 
                                :allow_destroy => true  
end

The lesson model.

class Lesson < ActiveRecord::Base
  attr_accessible :lesson_id, 
                  :lesson_type, 
                  :subject_code

  belongs_to :subject, 
             :class_name=>"Subject",
             :foreign_key=>"subject_code"

end

I am not sure where I went wrong with this implementation because I can't retrieve the lessons from a subject. My database table for Lesson already has a column for subject_code as well.

While messing around, I found that if for my subject model I make the following changes

  has_many :lessons,
           :foreign_key => "lesson_id"

I was able to retrieve the information about the lessons but with the lesson_id tied to the subject_id. However, having the foreign key changed to subject_code, it did not work and I am just confused as to why.

Any help would be appreciated.

like image 675
Butter Beer Avatar asked Jan 05 '13 06:01

Butter Beer


1 Answers

in Subject Model

has_many :lessons, :primary_key => "subject_code"
like image 124
shweta Avatar answered Oct 29 '22 17:10

shweta