2012-12-27 26 views
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) 

但是沒有返回屬於用戶朋友的課程。

我在塊的工作,所以如果我要使用,我將代碼。不過好像有一種方法可以在這裏用戶預先加載...

回答

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