1

我在视图中有一个块:

<% current_user.friends.each do |friend| %>
  <% friend.courses.each do |course| %>
    <%= course.course_name%>
  <% end %>
<% end %>

我正在阅读 Rails 指南和API,因为在我看来,这是我可以通过范围带入模型的东西。我有两个问题:

  1. 这是我可以通过范围带入模型的那种东西吗?
  2. 我该怎么做呢?

关系如下:

class User
  has_many :friends, through: friendships
  has_many :friendships, conditions: "status = 'accepted'"
  has_many :courses

class Course
  belongs_to :user

我尝试了几种不同的范围变化,特别是在课程模型中。我最近尝试的一个是:

scope :friend_courses, joins(:user => :friends)

但这并没有返回属于用户朋友的课程。

我在块中的代码有效,所以如果我必须使用它,我会的。但似乎有一种方法可以让用户在这里急切加载......

4

1 回答 1

1
class User < ActiveRecord::Base
  has_many :friend_courses, :through => :friends, :source => :courses
  has_many :friends, :through => :friendships
  has_many :friendships, :conditions => {:status => 'accepted'}
  has_many :courses
end

user.friend_courses
于 2012-12-28T00:03:51.127 回答