Problem with instance variables

Im developing a User model for my application (newbie stuff, but I have
to start somewhere). I followed the tutorial at
http://sonjayatandon.com/05-2006/how-to-build-a-secured-web-application-with-ruby-on-rails/
and decided to add an email field. The problem is that the email is not
being saved on the database and I end up with two email variables:
@email and email.

validates_presence_of :user_name, :password, :password_confirmation,
:email #:email was added by myself
validates_uniqueness_of :user_name

email getter

def email
@email
end

#email setter
def email=(eml)
emailRE= /[\w._%-]+@[\w.-]+.[a-zA-Z]{2,4}/
if eml =~ emailRE
@email = eml
else
# display error message
end
end

Check a sample output from the console:

july = User.new(:user_name => “july”, :password => “secret”, :password_confir
mation => “secret”)
=> #<User:0x358e3e0 @password_confirmation=“secret”,
@attributes={“ip2”=>nil, “a
ctive_user”=>0, “password_salt”=>“W9C7g8i+”, “validateip”=>true,
“ip2_updated”=>
nil, “password_hash”=>“75412fccdfc4dc313215913bf2789b67f6a23315”,
“user_name”=>"
july", “ip1_updated”=>nil, “ip1”=>nil, “email”=>“”}, @password=“secret”,
@new_re
cord=true>
july.email=“[email protected]
=> “[email protected]
july.email
=> “[email protected]
july
=> #<User:0x358e3e0 @password_confirmation=“secret”,
@email=“[email protected]”, @a
ttributes={“ip2”=>nil, “active_user”=>0, “password_salt”=>“W9C7g8i+”,
“validatei
p”=>true, “ip2_updated”=>nil,
“password_hash”=>“75412fccdfc4dc313215913bf2789b67
f6a23315”, “user_name”=>“july”, “ip1_updated”=>nil, “ip1”=>nil,
“email”=>“”}, @p
assword=“secret”, @new_record=true>

Regards,
Roberto

Roberto R. wrote:

email getter

def email
@email
end

#email setter
def email=(eml)
emailRE= /[\w._%-]+@[\w.-]+.[a-zA-Z]{2,4}/
if eml =~ emailRE
@email = eml
else
# display error message
end
end

Well you aren’t writing it ot the DB, you’re writing it to an instance
variable.

You are trying way too hard here. You (almost) never need explicit
getters and setters for database fields. Simply add the field to your
database table, and it magically becomes available with a getter and a
setter. No changes to your model necesary, at all. Active Record is
that cool.

And if you want that validation, just add a second line of validation
that looks like:

validates_format_of :email, :with => /[\w._%-]+@[\w.-]+.[a-zA-Z]{2,4}/