簡體   English   中英

Rails has_many和belongs_to與外鍵錯誤的關系

[英]Rails has_many and belongs_to relationship with foreign key error

我正在嘗試使用外鍵在rails上實現has_many和belongs_to關系,但是我在嘗試正確實現它時遇到了麻煩,任何幫助都將受到贊賞。 我也將此作為指南: http//guides.rubyonrails.org/association_basics.html

這兩個模型是主題和課程。 一門學科有很多課程,一堂課屬於一門學科。 外鍵是subject_code。

以下是相關代碼。

主題模型

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

課程模型。

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

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

end

我不確定這個實現在哪里出錯,因為我無法從主題中檢索課程。 我的Lesson數據庫表也有一個subject_code列。

在弄亂的時候,我發現如果我的主題模型我做了以下更改

  has_many :lessons,
           :foreign_key => "lesson_id"

我能夠檢索有關課程的信息,但是將lesson_id綁定到subject_id。 但是,將外鍵更改為subject_code,它不起作用,我只是為什么感到困惑。

任何幫助,將不勝感激。

在主題模型中

has_many :lessons, :primary_key => "subject_code"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM