Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Last active December 13, 2015 18:58
Show Gist options
  • Save Sephi-Chan/4959092 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/4959092 to your computer and use it in GitHub Desktop.
class Watchlist
# Will generate SELECT * FROM users WHERE id IN(SELECT user_id FROM watchlistings WHERE item_id = ...)).
# Instead of two queries (one to pluck the ids, the other to get the watchlistings.
def self.users_watching(item)
ids = Watchlisting.where(item_id: item.id).select(:user_id)
User.where(id: ids)
end
def initialize(user)
@user = user
end
# Same thing here.
def items
ids = Watchlisting.where(user_id: @user.id).select(:item_id)
Item.where(id: ids)
end
def add(item)
Watchlisting.create!(user_id: @user.id, item_id: item.id)
item
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment