2

I am using Ruby on Rails 4 and I have this User model:

require 'uuid'
UUID.state_file = false
UUID.generator.next_sequence

class User < ActiveRecord::Base
   attr_accessor :email, :password
   has_many :entries

   after_initialize do |user|
       user.entry_hash = UUID.new.generate
   end

end

Which is based on the following DB migration:

class CreateUsers < ActiveRecord::Migration

def change
    create_table :users do |t|
        t.string "email"
        t.string "password"
        t.string "entry_hash"
      t.timestamps
    end

  end
end

I want to automatically generate a uuid as a hash associated with that User.

Using the rails console to create a new User, I do the following:

1) I use create a User with an email and password:

irb(main):001:0> u = User.create(:email=>'[email protected]', :password=>'myPass')
   (0.1ms)  BEGIN
  SQL (0.6ms)  INSERT INTO `users` (`created_at`, `entry_hash`, `updated_at`) VALUES ('2013-12-07 22:32:28', '60744ec0-41bd-0131-fde8-3c07542e5dcb', '2013-12-07 22:32:28')
   (3.7ms)  COMMIT
=> #<User id: 2, email: nil, password: nil, entry_hash: "60744ec0-41bd-0131-fde8-3c07542e5dcb", created_at: "2013-12-07 22:32:28", updated_at: "2013-12-07 22:32:28">

2) But this is weird. If you look at the SQL, it doesn't insert anything but the entry_hash, and the output object shows email and password as nil. However, when I try to access those properties, I get the ones I put.

irb(main):002:0> u.email
=> "[email protected]"
irb(main):003:0> u.id
=> 2
irb(main):004:0> u.password
=> "myPass"
irb(main):005:0> u.entry_hash
=> "60744ec0-41bd-0131-fde8-3c07542e5dcb"

I am very new to Ruby on Rails and I know some magical stuff goes on in the background, but can someone enlighten me as to whats going on here? I just want to create an object with parameters.

Cheers

UPDATE: I fixed the problem I was having by removing the attr_accessor line. Anyone know why that made it work?

1 Answer 1

3

attr_accessor

  • Can be used for values you don't want to store in the database directly and that will only exist for the life of the object (e.g. passwords).

  • Is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.

The method create creates the row in the database and also returns the ruby object. That is why accessing the fields through the variable u worked, it is alive while the console is open. However, nothing made it to the database.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, that makes a lot of sense :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.