Rails Association的一个小谜题

时间:2016-03-25 03:41:27

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

有2张桌子。一个是Useridnameemail),另一个是Studentidwho_id)。< / p>

我想用这种方式:

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

而不是:

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

获取数据。

我该怎么办?

顺便说一下,我无法以任何理由将who_id更改为user_id

class User < ActiveRecord::Base
end

class Student < ActiveRecord::Base
end

1 个答案:

答案 0 :(得分:0)

您可以在学生模型中添加nameemail方法,如下所示:

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

您还可以使用Rail的委托方法在更少的代码中执行相同的操作:

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

一旦你正在工作,而不是Student.find(id).name, Student.find(id).email(它将从数据库中获取数据两次),你应该这样做:

student = Student.find(id) #single call to the database
# get the properties from the previous database call
student.name 
student.email
相关问题