【发布时间】:2011-08-27 15:52:58
【问题描述】:
我有一个 rails 3 应用程序。
我有以下场景:有学生和老师有互动。根据其中一些互动,教师可以选择给学生奖励,即 student_reward。
class Student
has_many :interactions
has_many :teachers, :through=>:interaction
class Teacher
has_many :interactions
has_many :students, :through=>:interaction
has_many :rewards
class Interaction
belongs_to :teacher
belongs_to :student
has_many :student_rewards
has_many :rewards, :through=>:student_reward
class Reward
belongs_to :teacher
has_many :student_rewards
class StudentRewards
belongs_to :reward
belongs_to :interaction
专家如何编写一种有效的方法来获取学生教师拥有的所有奖励 [不一定是学生赢得的奖励],并在显示屏上列出教师的信息?
我试过这个,但我必须在视图中单独获取教师信息,这很糟糕。 (假设 student_id=1):
@rewards = Reward.joins(:teacher => :interactions)
.where("interactions.student_id=1")
.paginate(:page => params[:page], :per_page => 5)
问题:
- 这是最好的方法吗?
- 当我在视图中遍历此内容时,我必须发出额外的查询以显示有关教师 [姓名、人口统计] 的信息。我怎样才能更有效地获取它?
我希望能够做到这一点:
<% for reward in @rewards%>
<%= reward.name, reward.teacher.name, reward.teacher.bio%><br>
<%end%>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord