Reputation: 1
def show_user_events
user = current_user
@join_events = JoinEvent.find_all_by_user_id(user.id)
# @events = Event.where(:id => @join_events)
respond_to do |format|
format.html # show_user_events.html.erb
format.json { render json: @events }
end
end
I want to get the specific values in the 'Event'. The 'event_id' is one of the attributes of the 'JoinEvent'. Using the 'event_id' values of '@join_events', I want to get the same effect as the command in the SQL query.
SELECT * FROM events
WHERE id in (join_events[1].event_id, join_events[2].event_id, ...)
What should I do to achieve this effect in rails?
Upvotes: 0
Views: 28
Reputation: 5929
There is at least two ways to do this implicitly or explicitly respectively:
JoinEvent.find([1, 2, 3]) # short for JoinEvent.where(id: [1, 2, 3])
JoinEvent.where(event_id: [1, 2, 3])
JoinEvent.where("event_id IN (?)", [1, 2, 3])
I prefer first approach when it's possible
Thus in your case you can collect ids
by:
@join_events = JoinEvent.where(user_id: current_user.id)
@join_events_ids = @join_events.pluck(:id)
or (more prefered way)
current_user.join_event_ids
Comes with has_many
association
collection_singular_ids
Returns an array of the associated objects’ ids
Upvotes: 1