0
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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

If I recall correctly, pluck works on Relation; not on Array. find_all_by_user_id will give you an array and pluck won't work on that.
Thank you for your answers :) It has been a great help to me.
0
JoinEvent.where(:event_id => [@join_events.map(&:id)])

2 Comments

With these extra [] you will get [[1, 2]]. Thus you don't need them
Thank you for your answers :) It has been a great help to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.