首先,我的模特:
User has_many :subscriptions
has_many :courses, :through => :subscriptions
Subscription belongs_to :both
Course has_many :subscriptions
has_many :users, :through => :subscriptions
要获得订阅的用户课程非常简单:
@subscribed_courses = current_user.courses
现在我想得到一个包含current_user与之无关的5个随机课程的列表(对于用户主页上的“你可能也喜欢...”功能)。最好的方法是什么?选择所有课程是否有效,然后在ruby中将哈希限制为仅在@subscribed_courses
实例变量中的课程?如果这是最好的方式,我该怎么做?
例如,Course.joins(:subscription)
将为我提供与订阅相关的所有课程。我想查询用户未订阅的课程,包括那些尚未订阅的课程(因此,与订阅无关)。对不起,我之前没有说清楚。
答案 0 :(得分:1)
Course.joins(:subscriptions).where('subscriptions.user_id <> ?', current_user.id).order('random()').limit(5)