I’ve two resources Team and Player. Player is a nested resource under Team in my routes.rb.
For Team, I have a show action with show.html.erb template. In that template, I have something like form_for [@team, @team.players.build], so basically I can create a new player from the team view.
Now what is the best way to code rendering/redirecting in the controller for Player#create on error? In a standard create action I would render the new action with errors:
if @player.save
redirect_to @player, notice: 'Player was successfully created.'
else
render action: 'new'
end
But now I’m now in a different controller (Player#create), while my form is in Team#show. If on error I redirect to @team, like on success, I will loose the error information stored in the instance variable. Is it better to try and render team/show.html.erb? This looks kind of messy. Or maybe add the create action for Player into the Team controller?
I see 3 options for you:
Use
flashto handle the error messages. You won’t have the instance variable available, but whatever you would have rendered can go inflash[:error]and used in Team#show.Use a remote request with a json response. You don’t need to redirect at all, just return a json object containing a partial for the new player (on success), or an error message (on error). Handle the response in the remote callback to update the page accordingly.
Move the player creation logic to the Team controller. I would do this only if none of the other options were viable.