what is attr_accessor in datamapper - ruby

2019-05-30 07:55发布

问题:

I am a newby in datamapper. I saw this code in this forum.

    class User
  include DataMapper::Resource

  property :id,                 Serial
  property :email,              String, :required => true, :unique => true, :format  => :email_address,
  property :name,               String
  property :hashed_password,    String
  property :salt,               String  
  property :created_at,         DateTime

  attr_accessor :password, :password_confirmation

property would mean that it defines the field in the database table..what does attr_accessor means..is it kind of field in the model but not in the database..

thanks

回答1:

Yes, you are right. It is an attribute (a field) of your model, but not in your database. You could use such attributes to keep data that shouldn't be saved in the database, but that somehow are useful for other objects in your application.

For example: you could define an accessor for a model field named "password". Then when someone sets this value, you hash it and store it in the appropriate field in the database.



回答2:

It looks like the password is not stored in the database, which is good.

The password is stored in the user object only when they say first login or when they are changing their password. Since a normal ruby sinatra app essentially boots on each page load, the password is only around while it gets hashed and put into the db, etc.

In other words you can often expect that a call to obtain the password will fail. It will only work if you are still handling the login or password change event.