Forum: Ruby on Rails Problem with instance variables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Roberto R. (Guest)
on 2006-06-04 21:47
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-se...
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="removed_email_address@domain.invalid"
=> "removed_email_address@domain.invalid"
>> july.email
=> "removed_email_address@domain.invalid"
>> july
=> #<User:0x358e3e0 @password_confirmation="secret",
@email="removed_email_address@domain.invalid", @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
Alex W. (Guest)
on 2006-06-04 22:02
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}/
This topic is locked and can not be replied to.