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.
in Subject Model
has_many :lessons, :primary_key => "subject_code"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With