我正在研究Hartl教程,但我遇到了一个问题。当我尝试在控制台中添加用户时,它不会返回已保存我刚刚输入的任何信息。代码如下,希望你们能引导我朝着正确的方向前进。 用户模型:
class User < ActiveRecord::Base
attr_accessor :name, :email
before_save { self.email = email.downcase}
validates :name, presence: true, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: {maximum: 255},
format: { with: VALID_EMAIL_REGEX },
uniqueness: {case_sensitive: false}
has_secure_password
validates :password, length: { minimum: 6 }
end
错误:
2.2.0 :003 > User.create(name: "Jim Bob", email: "jim@bob.com", password: "jimmybob", password_confirmation: "jimmybob")
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('jim@bob.com') LIMIT 1
SQL (0.4ms) INSERT INTO "users" ("password_digest", "created_at", "updated_at") VALUES (?, ?, ?) [["password_digest", "$2a$10$I61hwA3iAQmzsT/wbb0wpOSannOBNPLtQsBhscjakS5OgCi6zJoMq"], ["created_at", "2015-02-13 23:45:32.636129"], ["updated_at", "2015-02-13 23:45:32.636129"]]
(137.3ms) commit transaction
=> #<User id: 1, name: nil, email: nil, created_at: "2015-02-13 23:45:32", updated_at: "2015-02-13 23:45:32", password_digest: "$2a$10$I61hwA3iAQmzsT/wbb0wpOSannOBNPLtQsBhscjakS5...">
我不明白为什么名称和电子邮件不会保存。请任何帮助都会很棒。
答案 0 :(得分:1)
因为你已经为名称和电子邮件定义了attr_accessor。
attr_accessor将覆盖活动记录生成的方法,因此未将其保存到数据库中。