Rails model association problem, how to independently associate?

  mysql, question

I have two watches, one isUserThere areId,Name,Email.

The other one isStudentThere areId,who_id.

How can I set upStudentAndUserThe model association of.

So that I can finally use it

Student.find(id).name, Student.find(id).email

Instead of using

User.find(student.who_id).name, User.find(student.who_id).email

To get data?

PS: For some reason, I can’t transferStudenthit the targetwho_idinsteaduser_id, sorails g migrationWhen usinguser:referencesThis method cannot work.


class User < ActiveRecord::Base
 End
 
 class Student < ActiveRecord::Base
 End
class Student
 belongs_to :user, class_name: 'User', foreign_key: 'who_id'
 End

In order to obtain name under normal circumstances, it is necessary toStudent.find(student_id).user.name. If you want to get user name directly, you can add delegate method to Student. Such as

class Student
 belongs_to :user, class_name: 'User', foreign_key: 'who_id'
 delegate :name, to: :user
 End