2017-10-19 5 views
0

Voici mon schéma de base de données. NOTE la 'StudentID' et 'student_studentid'Comment définir des associations de tables personnalisées dans 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 

J'assigne id faits sur commande aux étudiants. Comment puis-je utiliser ces colonnes pour les associations de tables? Je veux être en mesure de dire TermReport.find ('my-id-10'). Étudiant.

Voici ce que j'ai essayé mais ne fonctionnera pas.

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

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

Répondre

0

Le problème ici est que vous utilisez l'attribut incorrect pour l'association. Vous pouvez regarder here plus de références

TermReport 
    belongs_to :student, foreign_key: studentid 

Student 
    has_many :term_reports, foreign_key: :stuent_studentid 
+0

TermReport.find ('jm-90'). L'étudiant ne fonctionne toujours pas Voir la sortie dans ma réponse. –

+0

vous pouvez vous référer à cela sur la façon de définir des clés primaires personnalisées pour l'étudiant https://stackoverflow.com/questions/32579245/creating-custom-primary-keys-in-rails-application – Maru

0

TermReport utilise toujours id comme clé primaire. Voir la sortie ci-dessous.

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