gpt4 book ai didi

ruby-on-rails - Rails 控制台正在添加 nil 而不是值

转载 作者:行者123 更新时间:2023-11-29 14:20:56 24 4
gpt4 key购买 nike

目前,当尝试通过 Rails 控制台或种子数据将新用户添加到我的用户表时,一切都是零。

在我运行的种子文件中:

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>

最佳答案

您的问题是在您的模型中使用 attr_accessor。这应该只用于你想为你不想存储在数据库中的对象定义 getter/setter 方法的地方。 See here获取更多信息。

删除以 attr_accessor 开头的整个行,您的代码将起作用。

同时删除 id 的分配和验证其存在的行。这是由数据库自动处理的。

关于ruby-on-rails - Rails 控制台正在添加 nil 而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com