In a Rails 7 controller create action I want to render the :new
action/view if the model.save action fails.
My initial code looked like this;
def create
new_city = City.new(params.require(:city).permit(:name, :prefecture_id))
respond_to do |format|
format.html do
if new_city.save
flash[:success] = "City saved successfully"
redirect_to city_index_path
else
flash.now[:error] = "Error: City could not be saved"
render :new, locals: { city: new_city }
end
end
end
end
This code would render the :new
action/view and pre-populate the form_with
element on that page with the values that the user had previously input (stored as the new_city
object). I also noticed that I can just render :new
without passing the locals
parameter and the form_with
element on that would still be pre-populated page with the values that the user had previously input. Nice.
else
flash.now[:error] = "Error: City could not be saved"
render :new
end
The flash.now[:error]
message would not render, though. I found a fix on github which works for rendering the flash.now
message.
else
flash.now[:error] = "Error: City could not be saved"
render :new, status: :unprocessable_entity
end
When I do this, however, the :new
view renders but the form_with
element is not pre-populated with the user input values. If I try to also pass in locals
then the status
stops working (therefore no flash message).
Is there a way that I can pass the status (so that the flash message works) and also the new_city
model (so that if the new_city.save
action fails then the form will re-render displaying the data that the user had previously input)?