Saving URL when submitting form fails in Ruby on Rails

I am currently working through various Rails tutorials, but everyone seems to recommend that a failed view form use a render to render the form with errors. For example, the create method looks like this:

def create @user = User.new(params[:user]) if @user.save flash[:success] = "Welcome to the Sample App" redirect_to @user else @title = "Sign up" render 'new' end end 

This has the desired effect, but means that if I have a new user form in http: // localhost: 3000 / users / new and an error occurs, I get the same form with errors in http: // localhost: 3000 / users

Is there any way to make sure that I go to http: // localhost: 3000 / users / new ?

I was thinking of using redirection instead of render 'new', but this could cause problems with displaying form errors. Someone from IRC Rails directed me to a way to test clients, but it seems like this is avoiding the problem.

+4
source share
3 answers

I had a similar problem with my user registration form. Since I do not use RESTful routes there, I was able to resolve it along the following routes:

 resources :users, :except => [:new, :create] do ... end get "/signup" => "users#new" post "/signup" => "users#create" 

and in a new form:

 form_for @user, :url => signup_path do ... 
+2
source

Try redirect_to :action => 'new' instead of just rendering, this will save the url, but the error information will be lost (unless you put it in flash ).

Another option is to submit the URL form, which is used to display it. At the beginning of the action, you check if there is any data that you need to process. If the processing went fine, you redirect_to somewhere else, otherwise you won’t do anything - the form will be displayed along with all errors. This, I suppose, is not very Railsy, ​​but it should work the way you want.

+1
source

Sorry for being late (only 6 years old) for the party, but somehow this seems like a problem with Turbolinks .

See these issues here and here .

+1
source

All Articles