How to stay at the same URL when validation fails

I use Ruby on Rails 2.3.8, and I have a registration form in which I get the parameter as follows: /registration/4 , which 4 is the identifier of the user who recommended the user who is going to register on the website.

The problem is that if the check fails when the user submits the registration (the form is displayed on the users controller, the create_particular action), the site is redirected to /users/create_particular , and therefore I lose the parameter with the value 4, which I had before. Also, I want the user to stay at the same URL as /registration/4

How can i do this?

+4
source share
5 answers

Then you have to rewrite your creation method. You should use redirect_to :back instead of render :action

UPD

 def new @word = Word.new(params[:word]) @word.valid? if params[:word] end def create @word = Word.new(params[:word]) if @word.save redirect_to @word else redirect_to new_word_path(:word => params[:word] ) end end 

It looks pretty dirty, but it's just a scratch

UPD 2

This is not really the best solution, but it works

 # routes.rb match 'words/new' => 'words#create', :via => :post, :as => :create_word # words_controller def new @word = Word.new end def create @word = Word.new(params[:word]) respond_to do |format| if @word.save format.html { redirect_to(@word, :notice => 'Word was successfully created.') } else format.html { render :action => "new" } end end end # views/words/new.html.erb <%= form_for(@word, :url => create_word_path) do |f| %> ... <% end %> 
+3
source

Send the current URI (for example, action = ""). When the feed is valid, redirect. POST-> Redirect-> GET is a good habit.

+2
source

From the head:

Change your controller (file registrations_controller.rb). The Create method by default contains the following code fragment:

 if @registration.save format.html { } format.xml { } else format.html { } format.xml { } end 

Add redirect_to (:back) between the brackets in else format.html{}

0
source

Ok, I solved the problem by doing the following:

1) I created two routes with the same path, but with a different condition method (one after it, and the other configured to receive)

2) I changed the form to post this POST action defined above

3) I added render =>: my_action when the check failed

So pretty much that.

Thanks anyway for your help.

0
source

Hidden field. This user ID parameter has a name with which you retrieve it into your controller, right? So just put this value in a hidden field with the same name, then it will endure a trip around the world.

For instance:

 <%= hidden_field_tag :referring_user_id, params[:referring_user_id] %> 
0
source

Source: https://habr.com/ru/post/1338151/


All Articles