I am creating suggestions in my app as usual:
class SuggestionsController < ApplicationController
def create
@suggestion = current_user.suggestions.new(params[:suggestion])
if @suggestion.save
render :show, status: :created
else
render :error, status: :unprocessable_entity
end
end
end
Each suggestion belongs to a service (the service_id is sent to the create action in the params[:suggestion]).
When I return the suggestion to the client, I would like to include the details of the suggestion’s service in the JSON. This means that I should eager load it somewhere to save on database requests.
This would be fine if I was finding the suggestion:
Suggestion.includes(:service).find(params[:id])
Can I do something similar on saving?
@suggestion = current_user.suggestions.new(params[:suggestion])
# This doesn't work.
@suggestion.includes(:service).save
you can do this as part of default scope in your suggestion model