将块转换为范围

时间:2012-12-27 20:11:32

标签: ruby-on-rails-3 activerecord scope associations

我在视图中有一个块:

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

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

  1. 这是我可以通过范围引入模型的那种东西吗?
  2. 我该怎么做呢?
  3. 关系如下:

    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 个答案:

答案 0 :(得分: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
相关问题