[Rails] Rails 101 - Validation
Stefan Arentz
stefan.arentz at norad.org
Fri Dec 10 08:08:34 GMT 2004
I'm trying to figure out what the standard pattern is for simple form
management.
Consider the following table:
table country:
int id
int code
varchar name
Like:
1 45 Denmark
2 31 The Netherlands
I have a controller to add a new one:
class CountriesController
def add
@country = Country.new
end
def add_post
@country = Country.new(@params["country"])
if @country.save then
redirect_to(:action => "list")
else
render_action "add"
end
end
end
With a simple form: (the show error is a test of a helper that shows an
optional error)
<form action="add_post" method="post">
Code: <%= text_field("country", "code") %> <%= show_error(@country,
"code") %><br>
Name: <%= text_field("country", "name") %><br>
<input type="submit" value="Add country">
</form>
Ok all looks simple. But my problem is with validation. My Country
model object looks like this:
class Country < ActiveRecord::Base
def validate
errors.add("code", "invalid") unless code =~ /[0-9]*/;
end
end
There are two problems with this code:
When I call /countries/add, the code form field is initialized to 0. I
don't want to have a default value in there. Where does it come from?
Also, when I submit the form with the code form field set to '123a',
the validation correctly kicks in and sets the error message. But it
also resets the code field to '0'. The name field is displayed
correctly however.
I'm not sure what I'm doing wrong here.
S.
More information about the Rails
mailing list