1

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

  • Can you add your layout code? – Vi. Nov 03 '22 at 08:43
  • 1
    my guess is that new_city is not an environment variable, then it can't be used in the view. You can change your variable `new_city` to `@new_city` also you have to make sure your :new view is using this environment variable in the form. – Maxence Nov 03 '22 at 10:40
  • 1
    Great ! (Although I meant instance variable, not environment variable) – Maxence Nov 04 '22 at 07:00

0 Answers0