0

Here is my DB Schema. NOTE the 'studentid' and 'student_studentid'

  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

I am assigning custom id's to the students. How can I use these columns for table associations? I want to be able to say TermReport.find('my-id-10').student.

Here is what I have tried but wont work.

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

class Student < ActiveRecord::Base
 has_many :term_reports, primary_key: :stuent_studentid
end
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John Milo
  • 47
  • 1
  • 8

2 Answers2

0

The problem here is that you are using the incorrect attribute for the association. You can look here for more references

TermReport
  belongs_to :student, foreign_key: studentid

Student
  has_many :term_reports, foreign_key: :stuent_studentid
Maru
  • 590
  • 5
  • 14
  • TermReport.find('jm-90').student still doesn't work See the output in my answer. – John Milo Oct 19 '17 at 11:57
  • you can refer to this on how to set custom primary keys for student https://stackoverflow.com/questions/32579245/creating-custom-primary-keys-in-rails-application – Maru Oct 19 '17 at 11:58
0

TermReport is still using id as its primary key. See the output below.

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
John Milo
  • 47
  • 1
  • 8