Reputation: 1894
First, my models:
User has_many :subscriptions
has_many :courses, :through => :subscriptions
Subscription belongs_to :both
Course has_many :subscriptions
has_many :users, :through => :subscriptions
To get the User's courses that are subscribed is easy enough:
@subscribed_courses = current_user.courses
Now I want to get a list of 5 random courses that the current_user is not associated with (for a "You might also like..." function on the user's homepage). What's the best way to do this? Would it be performant to select all Courses and then, in ruby, limit the hash to just the courses not in the @subscribed_courses
instance variable? How would I do that if it's the best way?
For example, Course.joins(:subscription)
will give me all courses associated with a subscription. I want to query for courses that the user is not subscribed to, including those courses that no one has subscribed to yet (and so, aren't associated with a subscription). Sorry I didn't make that clearer before.
Upvotes: 0
Views: 67
Reputation: 10018
Course.joins(:subscriptions).where('subscriptions.user_id <> ?', current_user.id).order('random()').limit(5)
Upvotes: 1