How to carry parameters to a new page?


#1

Hello,

I have a page where user can register him/herself to the site.

If the user enters something wrong, or leaves blank textboxes, I want to
reload the page and tell the user what went wrong. Also the
textbox-values the user already entered, should be kept in the
textboxes.

For example, in my user-controller:

if @username.length == 0
redirect_to :action => ‘registeruser’, :message => “You must give an
username”

This gives the url:
“/user/registeruser?message=You+must+give+an+username” and I can show
the message with <%=h @params[‘message’]%>.

Is this THE way to go, just add the values from textboxes to the url
also? Or is there a way I can do this without using the url-parameters?


#2

You could do:

if @username.length == 0
@session[:error]=“You must give an username”
redirect_to :action => ‘registeruser’
end
and then use @session[:error] to access the error


#3

Hi,

On 9.1.2006, at 15.01, Dzei wrote:

For example, in my user-controller:
Is this THE way to go, just add the values from textboxes to the url
also? Or is there a way I can do this without using the url-
parameters?

The Rails way of doing this is not to redirect. If there’s something
wrong with the input data, just re-display the same form:

in the controller:

@user = User.new(params[:user])

if @user.save
redirect_to somewhere_else
else
# the user input was invalid
flash.now(:error) = “There was a problem with your input”
render :action => “add_user”
end

Now the add_user template (the same you used in the original form
page) will have an invalid @user object at hand. If you used the
Rails form helper methods like text_field (you did, didn’t you?), the
fields with error will be automatically marked as erroneous. You can
also display error_messages_for, which will output a list of all
fields that were invalid.

Oh, and you shouldn’t have to do things like

if @username.length == 0
redirect_to :action => ‘registeruser’, :message => “You must
give an
username”

yourself. Validations like this belong to the model and the above-
mentioned depends on the model validations. See the api docs for
validations [1] for more info.

//jarkko

[1] http://api.rubyonrails.com/classes/ActiveRecord/Validations.html


#4

Thank you all for your answers.

And yes I ordered the Agile Web D. with Rails last week. I hope
it ships soon. :slight_smile:


#5

You should really read Agile Web D. with Rails. Using flash
messages
is one of the first things discussed, and if your form was built with
scaffolding, then the support is already there.