1

ビューにブロックがあります:

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

Rails Guides とAPIを読んでいたのは、スコープを介してモデルに取り込めるもののようなものだと思ったからです。2 つの質問があります。

  1. これは、スコープを介してモデルに持ち込めるもののようなものですか?
  2. どうすればそれを行うことができますか?

関係は次のとおりです。

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

class Course
  belongs_to :user

特に Course モデルでは、いくつかの異なるスコープのバリエーションを試しました。最近試したのは次のとおりです。

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 に答える