2

I have a form in my Rails app with a very straightforward controller and if the form cannot save, I'd like to render :new to show the errors:

def create
    @health_profile = HealthProfile.new(health_profile_params)

    if @health_profile.save
        redirect_to :somewhere_else
    else
        render :new
    end
end

This works great, but the URL goes from /health_profiles/new to /health_profiles following the attempt to create a record. Is there a way to call render :new and have the URL reflect that the user is at /health_profiles/new? If they were to refresh the page while the URL shows /health_profiles, it would load the :index which is not what I want.

Jeremy Thomas
  • 5,590
  • 8
  • 40
  • 80

2 Answers2

1

Not really. You basically have three options:

  1. You can use JS to change the URL after you re-render the new view.

  2. You can change your render to a redirect_to but you'll lose the errors in @health_profile so you'd have to rely on the flash to show your errors.

  3. You could change all your routes so that you can POST/PUT to the new route and put some conditional logic in your new action to branch based on the request.method

smathy
  • 23,746
  • 5
  • 45
  • 66
1

Because you are submitting a form (to URL which is in "action" attribute of form). This is normal. Don't change the URL.

Igor Kasyanchuk
  • 728
  • 5
  • 12