Reputation: 4740
I'm using Ruby on Rails 2.3.8 and I've got a registration form in which I receive a parameter as follows: /registration/4
, which 4 is the id of a user who recommended the user that is about to register in the website.
The problem is that if the validation fails when the user submits the registation (the form renders to the controller users
, action create_particular
) the site will redirect to /users/create_particular
, and therefore I lose the parameter with value 4 that I had before. Besides, I want the user to stay at the same url, which is /registration/4
How can I do that?
Upvotes: 4
Views: 3062
Reputation: 5173
Hidden field. That user ID param has a name by which you extract it in your controller, right? So just put that value in a hidden field of the same name, then it will survive a round-trip.
For example:
<%= hidden_field_tag :referring_user_id, params[:referring_user_id] %>
Upvotes: 0
Reputation: 83680
Then you should rewrite your create 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
Looks quite dirty, but this is just a scratch
UPD 2
This is really not 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 %>
Upvotes: 3
Reputation: 4740
Ok I solved the problem by doing the following:
1) I created two routes with the same path, but with different conditions method (one it's post and the other one is set to get)
2) I changed the form in order to post to the POST action defined above
3) I added render => :my_action when the validation fails
So that's pretty much it.
Thanks anyway for all your help.
Upvotes: 0
Reputation: 11751
Submit to the current URI (e.g. action=""). When the submission is valid, redirect. POST->Redirect->GET is a good habit.
Upvotes: 2
Reputation: 2984
From the top of my head:
Edit your controller (registrations_controller.rb file). Create method by default contains following piece of code:
if @registration.save
format.html { }
format.xml { }
else
format.html { }
format.xml { }
end
Add redirect_to (:back)
between brackets to else format.html{}
Upvotes: 0