Rails 关联的小谜题
A small puzzle of Rails Associations
有2张桌子。一个是 User
(id
, name
, email
) 另一个是 Student
(id
, who_id
).
我想这样使用:
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
您可以在 Student 模型中添加 name
和 email
方法,如下所示:
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
有2张桌子。一个是 User
(id
, name
, email
) 另一个是 Student
(id
, who_id
).
我想这样使用:
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
您可以在 Student 模型中添加 name
和 email
方法,如下所示:
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