1

I'm new to Ruby on Rails and following the blog tutorial I have noticed that it separates out new and edit from create and update. This is fine, but what I'm finding is that if the validation kicks in and the save fails, Rails returns the user back to the form with the errors... BUT it's actually showing a different URL now because the form isn't pointing to the same page.

So for example, the user goes to: /articles/new and then submits the form without filling in any of the fields. The form (as per the rails docs) is pointing to /articles which means the user ends on that url but in the controller it is told to render the new form and refreshing the page will continue to show that new form.

My first question is why is the new form being rendered even after further refreshes of the /articles page? Surely after refresh (it's not resubmitting the data) it should then be just showing the index action (as that's the url I am on). However clicking into the browser address bar and hitting return does then re-show the index controller action method. So what is refresh doing differently? And how come I don't get the usual browser popup saying you are resubmitting data on refresh?

The second question... Is it possible to prevent those urls from changing? So if the user goes to: articles/1/edit and submits invalid data they remain on the same page and NOT taken to articles/1.

Here is the create method:

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      #redirect_to new_article_path
      render 'new'
    end
  end

I tried to solve the issue by redirecting the user back to the new page instead of just rendering the new view. But this looses the errors...

The routes are as follows:

  resources :articles do
    resources :comments
  end
Cameron
  • 24,868
  • 91
  • 263
  • 449
  • For your first question: http://stackoverflow.com/a/14491231/2688575. For your second question: http://stackoverflow.com/a/4708730/2688575 – Huy Bui Jun 27 '16 at 11:46

1 Answers1

0

First answer: refresh after an POST makes that the browser to resend the form to the server with the exact same parameters than before and therefore the result is the same. Whereas clicking into the address bar and hinting enter makes a normal GET request to that URL.

Second answer: Yes, that would be possible, but that you are on your own. You would have to define your routes yourself, because you cannot use Rails' restful resources anymore. And you might need to change the behavior of the link_to method or some form helpers.

I would argue that it is not worth it to fight against Rails conventions.

spickermann
  • 81,597
  • 8
  • 83
  • 112