2017-10-19 69 views
0

這是我的DB模式。 注意 'studentid' 和 'student_studentid'如何在Rails中設置自定義表關聯

create_table "students", force: true do |t| 
    t.string "fname",  limit: 45 
    t.string "lname",  limit: 45 
    t.string "guardian", limit: 45 
    t.string "phone",  limit: 45 
    t.string "email",  limit: 45 
    t.integer "user_id" 
    t.date "createdate" 
    t.string "studentid", limit: 45 
    end 

    create_table "term_reports", force: true do |t| 
    t.string "student_studentid", limit: 10 
    t.integer "subject_id" 
    t.integer "score" 
    t.integer "position" 
    t.integer "term" 
    t.integer "year" 
    t.integer "user_id" 
    t.date "ceatedate" 
    end 

我指定自定義的ID給學生。我如何將這些列用於表關聯?我想能夠說TermReport.find('my-id-10')。student

這是我試過的,但不會工作。

class TermReport < ActiveRecord::Base 
belongs_to :student, :primary_key => :studentid 
end 

class Student < ActiveRecord::Base 
has_many :term_reports, primary_key: :stuent_studentid 
end 

回答

0

這裏的問題是您正在使用不正確的關聯屬性。您可以查看here以獲取更多參考信息

TermReport 
    belongs_to :student, foreign_key: studentid 

Student 
    has_many :term_reports, foreign_key: :stuent_studentid 
+0

TermReport.find('jm-90')。學生仍然無法正常工作請參閱我的答案中的輸出。 –

+0

你可以參考這個如何爲學生設置自定義主鍵https://stackoverflow.com/questions/32579245/creating-custom-primary-keys-in-rails-application – Maru

0

TermReport仍將ID用作其主鍵。請參閱下面的輸出。

TermReport.find('jm-90').student 

TermReport Load (0.7ms) SELECT `term_reports`.* FROM `term_reports` WHERE `term_reports`.`id` = 0 LIMIT 1 
ActiveRecord::RecordNotFound: Couldn't find TermReport with 'id'=jm-90