Given a model called Event (id, name) and a model called EventUser (event_id, user_id), I iterate through Events. During this iteration, I display whether or not the logged-in user is attending the Event based on the existence of an EventUser existing. Standard stuff.
I know that I can perform a query against each Event, and have something such as
class Event < ActiveRecord::Base
def user_attending?(user)
event_users.find_by(:user_id => user.id)
end
end
but that's not very clean, performant, or extensible.
I could load all of the User's attending events from the list of Events, say,
@events = Event.all
@attending_events = current_user.event_users.where(:event_id => @events.map(&:id))
which is better, but not great. I could with this add an accessor to my Event model and iterate through @attending_events
but that seems icky.
I suppose in my ideal scenario, I would be able to join the two tables on events.id = event_users.event_id
, and where event_users.user_id = current_user.id
and if that row exists, I'd be able to label the/a resulting column as attending
How can I do this with Arel or ActiveRecord, or even SQL? Using PostgreSQL over here.