0

I have the following query which looks up an organisation belonging to the current signed in user and then finds any events belonging to that organisation.

def update
    @organisation = current_user.organisations.find(params[:organisation_id])
    @event = @organisation.events.find(params[:id])
    if @event.update_attributes(params[:event])
        # Handle a successful update.
        flash[:success] = "Event updated"
        redirect_to organisation_event_path
    else
        render 'edit'
    end
end

This currently results in 2 queries to the database, which whilst not necessarily a problem, I feel should be able to be achieved in one query. Is that possible or does it need to be 2? If the former, how should I go about achieving it?

2 Answers 2

1

The query could be refactored in this way:

def update
    @event = Event.joins(:organisations).where("id = ? AND organisation_id = ? AND user_id = ?", params[:id], params[:organisation_id], current_user.id).first()
    if @event.update_attributes(params[:event])
        # Handle a successful update.
        flash[:success] = "Event updated"
        redirect_to organisation_event_path
    else
        render 'edit'
    end
end
Sign up to request clarification or add additional context in comments.

Comments

1

It should work:

current_user.organisations.joins(:events).where(["id = ? AND events.id = ?", params[:organisation_id], params[:id]]).first()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.