I'm following Michael's Ruby on Rails tutorial (Chapter 6.2.2) and when I go to the rails console --sandbox
to attempt to create Users the outputs come totally outdated.
I update a user's attribute, I return the user and the console outputs nil
for all attributes. However if I output the user.attribute
the data is there.
The first save fails because a user must have a name, though I had this problem even before addind validations.
What am I missing here? I followed all the instructions and I'm doing pretty basic stuff. I'm executing the following commands:
$ rails console --sandbox
Loading development environment in sandbox (Rails 4.0.2)
Any modifications you make will be rolled back on exit
2.1.0 :001 > user = User.new(name: "", email: "mhartl@example.com")
=> #<User id: nil, name: nil, email: nil, citizen_number: nil, created_at: nil, updated_at: nil>
2.1.0 :002 > user.save
(0.1ms) SAVEPOINT active_record_1
(0.2ms) ROLLBACK TO SAVEPOINT active_record_1
=> false
2.1.0 :003 > user.valid?
=> false
2.1.0 :004 > user.name = "Bob"
=> "Bob"
2.1.0 :005 > user.valid?
=> true
2.1.0 :006 > user
=> #<User id: nil, name: nil, email: nil, citizen_number: nil, created_at: nil, updated_at: nil>
2.1.0 :007 > user.save
(0.2ms) SAVEPOINT active_record_1
SQL (6.2ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Sat, 08 Feb 2014 19:15:37 UTC +00:00], ["updated_at", Sat, 08 Feb 2014 19:15:37 UTC +00:00]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> true
2.1.0 :008 > user
=> #<User id: 1, name: nil, email: nil, citizen_number: nil, created_at: "2014-02-08 19:15:37", updated_at: "2014-02-08 19:15:37">
My user model:
class User < ActiveRecord::Base
attr_accessor :name, :email, :citizen_number
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
VALID_CITIZEN_NUMBER_REGEX = /[1-9]\d{7,}/
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :citizen_number, presence: true, format: { with: VALID_CITIZEN_NUMBER_REGEX }, uniqueness: true
before_save { lowercase_email() }
def lowercase_email()
self.email = email.downcase
end
end