Note that there are some explanatory texts on larger screens.

plurals
  1. PORails -- self vs. @
    primarykey
    data
    text
    <p>I am following Michael Hartl's RoR tutorial, and it is covering the basics of password encryption. This is the User model as it currently stands:</p> <pre><code>class User &lt; ActiveRecord::Base attr_accessor :password attr_accessible :name, :email,: password, :password_confirmation email_regex = /^[A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/ #tests for valid email addresses. validates :name, :presence =&gt; true, :length =&gt; {:maximum =&gt; 50} validates :email, :presence =&gt; true, :format =&gt; {:with =&gt; email_regex}, :uniqueness =&gt; {:case_sensitive =&gt; false} validates :password, :presence =&gt; true, :length =&gt; {:maximum =&gt; 20, :minimum =&gt; 6}, :confirmation =&gt; true before_save :encrypt_password private def encrypt_password self.encrypted_password = encrypt(password) end def encrypt(string) string end end </code></pre> <p>I posted a previous question about <code>before_save</code> not working, and it turns out that what I had accidentally done is written my encrypt_password as:</p> <pre><code>def encrypt_password @encrypted_password = encrypt(password) end </code></pre> <p>I understand that if self.encrypted_password sets the encrypted_password attribute, but why does @encrypted_password not do that as well? In the response to the previous post about <code>before_save</code> not working someone said that the instance variable was "forgotten" after the method ended with the way I had originally coded it -- why was this the case? Can someone please explain how self and @ work differently <strong>in the context of the code above?</strong></p> <p>NOTE: I already took a look at the posts <a href="https://stackoverflow.com/questions/1693243/instance-variable-self-vs">here</a> and <a href="https://stackoverflow.com/questions/4639271/ruby-self-vs">here</a>, but they both say that "self" is calling the <code>attribute =</code> method, and I don't even understand how that method could exist here since I never created it or declared the encrypted_password w/ <code>attr_accessor</code>. So I am still confused, and <strong>this is not a re-posting of those questions.</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload