ruby - Rails Tutorial : 6.3.1 An encrypted password -
i going though tutorial (which must excellent resource) , don't quite understand following:
in section 6.3.1 create password_digest column in db via creating , running migration script via :
rails generate migration add_password_digest_to_users password_digest:string bundle exec rake db:migrate bundle exec rake db:test:prepare bundle exec rspec spec/ then on rails console able instantiate user model object , set password_digest on :
irb(main):007:0> @user = user.new => #<user id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil> irb(main):008:0> @user.password_digest = "zzzz" => "zzzz" irb(main):009:0> @user.password_digest => "zzzz" however can not see password_digest property on user model class definition :
class user < activerecord::base attr_accessible :email, :name before_save { |user| user.email = email.downcase} valid_email_regex = /\a[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :name, presence: true, length: {maximum: 50} validates :email, presence: true, format: { with: valid_email_regex}, uniqueness: {case_sensitive: false} end i imagine rails doing magic under covers, mind explaining it's doing?
thanks!
you right - what's going on here is rails magic behind scenes.
whenever have descendant of activerecord::base activerecord @ database table class , automatically create accessors - won't show in class definition. seems crazy if you're coming language c# had kind of stuff manually before.
what activerecord doing (this very watered down explanation, actual thing more complicated) kind of sticking following code in class:
class user < activerecord::base def password_digest @password_digest end def password_digest=(val) @password_digest = val end end the other thing note doesn't creation of attribute getter , setter - mixes in type casting based on type of column. check out this question more info , possible gotchas.
the net result of kind of bonus, , 1 of reasons rails: define column once in database, , put model class free.
this pattern common rails though, , you'll see often. if still learning ruby or rails framework , aren't 100% sure comes from, don't afraid more closely - so-called rails 'magic' occurs , takes time not surprised. had experience when first moved rails other languages.
Comments
Post a Comment