Sung-Jun Kim
Sung-Jun Kim

Reputation: 1

How Could I use SQL IN command in Rails?

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

Answers (2)

ck3g
ck3g

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

kiddorails
kiddorails

Reputation: 13014

JoinEvent.where(:event_id => [@join_events.map(&:id)])

Upvotes: 0

Related Questions