-3

There are 2 tables. One is User(id, name, email) and the other is Student(id, who_id).

I wanna Use this way:

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

rather than:

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

to get data.

How should I do?

btw, I cannot change who_id to user_id for any reason.


class User < ActiveRecord::Base
end

class Student < ActiveRecord::Base
end

1 Answers1

0

You can add name and email methods in your Student model, like so:

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

  def name
    user.name
  end

  def email
    user.email
  end
end

You could also use Rail's delegate method to do the same thing in less code:

class Student < ActiveRecord::Base
  belongs_to :user, class_name: :User, foreign_key: 'who_id'
  delegate :name, to: :user
  delegate :email, to: :user
end

And once you ge tthat working, rather than Student.find(id).name, Student.find(id).email (which will fetch the data from the database twice) you should instead do this:

student = Student.find(id) #single call to the database
# get the properties from the previous database call
student.name 
student.email
joshua.paling
  • 13,762
  • 4
  • 45
  • 60
  • Yes, this is a good method, but I am thinking whether we can create bidirectional models connecting, so that `student.id` will auto delete when `user.id` is destroyed. That is add `dependent: :destroy`. Can we ? Thanks! – Neutral Ceeps Mar 25 '16 at 04:09
  • I think this question covers that: http://stackoverflow.com/questions/15939799/has-one-has-many-with-dependent-destroy-but-using-a-different-name-for-the-key – joshua.paling Mar 25 '16 at 06:42