目前,当尝试通过rails console或种子数据向我的User表添加新用户时,一切都是零。
在我的种子文件中,我正在运行:
u1 = User.create(:from_email => "v@gmail.com", :to_email => "s@gmail.com", :from_name=>"Vero", :to_name=>"Spencer", :message=>"Test message", :password=>"chicken", :id => 1)
u1.save!
如果我通过rails或rails控制台中的种子数据运行它,然后使用User.all检查Postgres数据库,我得到:
#<User id: 1, from_name: nil, to_name: nil, from_email: nil, to_email: nil, message: nil, created_at: "2014-12-10 02:34:02", updated_at: "2014-12-10 02:34:02", password: nil>
我已经处理了好几个小时,开始变得很困惑。帮助将不胜感激,我的模型和架构如下:
class User < ActiveRecord::Base
attr_accessor :from_name, :from_email, :to_name, :to_email, :message, :password, :id
before_save { self.from_email = from_email.downcase }
before_save { self.to_email = to_email.downcase }
before_save { self.password = "merrychristmas#{ Random.rand(1000) }" }
validates :id, :presence => true, :uniqueness => true
validates :from_name, :presence => true, :uniqueness => false
validates :to_name, presence: true, :uniqueness => false
validates :from_email, presence: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i}
validates :to_email, presence: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
validates :message, presence: true, length: { maximum: 50 }
def self.authenticate(id, password)
user = find(id)
if user && user.password
user
else
nil
end
end
端
架构:
ActiveRecord::Schema.define(version: 20141209104326) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "users", force: true do |t|
t.string "from_name"
t.string "to_name"
t.string "from_email"
t.string "to_email"
t.text "message"
t.datetime "created_at"
t.datetime "updated_at"
t.string "password"
end
end
SQL
(0.3ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."id" = 2 LIMIT 1
SQL (0.4ms) INSERT INTO "users" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-12-10 04:15:33.579478"], ["updated_at", "2014-12-10 04:15:33.579478"]]
(6.5ms) COMMIT
=> #<User id: nil, from_name: nil, to_name: nil, from_email: nil, to_email: nil, message: nil, created_at: "2014-12-10 04:15:33", updated_at: "2014-12-10 04:15:33", password: nil>
答案 0 :(得分:3)
您的问题是在模型中使用attr_accessor
。只应在要为不希望存储在数据库中的对象定义getter / setter方法的情况下使用此方法。 See here了解更多信息。
删除所有以attr_accessor
开头的行,您的代码就可以使用。
同时删除id
的分配以及验证其存在的行。这由数据库自动处理。
答案 1 :(得分:0)
你没有身份证吗?该字段由db自动递增。所以基本上删除所有引用:id =&gt; 1和:验证:id ....
答案 2 :(得分:0)
从模型.rb文件中删除attr_accessor应该可以。