Q:

Rails 3, adding joins to default_scope for association of current_user

In my app i have a schema of Users and Tickets, each User can be subscribed to many Tickets and viceversa.
For each ticket i fetch from the database, i want to display if current_user is subscribed or not to the ticket itself.
An example of my query is as follows:
@tickets = current_user.tickets.limit(10).order('created_at DESC')

Can i do it using a default_scope with a join in Ticket model?, i need it to return an additional field with a simple true or false, or nil.
Thank you.

A:

Example 1 - To figure out whether an individual ticket is subscribed:
ticket = Ticket.find(id)
@ticket_is_subscribed = current_user.tickets.any? { |t| t == ticket }

Example 2 - If you want simply an array with all ticket IDs subscribed by the current user:
subscribed_ids = current_user.tickets.pluck(:id)
@ticket_is_subscribed = subscribed_ids.include?(ticket.id)

Example 3 - You could generate an array of arrays that gives you true or false for each ticket.id.
subscribed_ids = current_user.tickets.pluck(:id)
@all_subscribed_tickets = Ticket.all.pluck(:id).map { |id| [id, subscribed_ids.include?(id)] }

