我正在构建的应用程序包含一个联系表单。播种时会生成一条我不理解的错误消息:
ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint
DETAIL: Failing row contains (1, null, null, null, 2015-06-06 13:43:12.339477, 2015-06-06 13:43:12.339477).
: INSERT INTO "messages" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"
以下是表单的相关代码。如果我从模型文件中删除行attr_accessor :name, :email, :content
,它就会成功播种(我不知道为什么这会对播种产生影响)。但即便如此,在开发服务器上,如果我转到联系表单并提交没有任何值,则错误消息似乎无法正常运行。无论错误如何,它只会给出一条错误消息“传递此消息时发生错误”,而对于所有其他形式,错误消息指定了变量和错误类型。可能导致这种行为的原因是什么?
联系表格的模型文件:
class Message < ActiveRecord::Base
attr_accessor :name, :email, :content
validates :name, presence: true,
length: { maximum: 255 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true,
length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
validates :content, presence: true,
length: { maximum: 600 }
end
迁移文件包括:
t.string :name, null: false, limit: 255
t.string :email, null: false, limit: 255
t.string :content, null: false, limit: 600
在我的种子文件中,我有:
Message.create!(email: "example@example.com",
name: "Example User",
content: "This is my message")
更新:关于错误消息,我有以下控制器方法:
def create
@message = Message.new(message_params)
if @message.valid?
MessageMailer.new_message(@message).deliver_now
flash[:success] = "Your messages has been sent."
redirect_to contact_path
else
flash[:alert] = "An error occurred while delivering this message."
render 'new'
end
end
我删除了闪光警报线。我有其他正常运行的表单,也没有这一行,虽然这个flash消息可能会覆盖其他更具体的错误消息。删除此行并提交无效信息后,表单只会使无效字段变为红色,但根本不显示任何错误消息。在其他形式中,我会例如得到这些错误消息:
The form contains 5 errors.
Email can't be blank
Email is invalid
Username can't be blank
Username is too short (minimum is 6 characters)
Username is invalid
日志文件是:
Started GET "/contact" for xx.xxx.xx.xxx at 2015-06-06 14:15:43 +0000
ActiveRecord::SchemaMigration Load (0.5ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by MessagesController#new as HTML
Rendered messages/new.html.erb within layouts/application (493.2ms)
Rendered layouts/_shim.html.erb (0.4ms)
Rendered layouts/_header.html.erb (10.5ms)
Rendered layouts/_footer.html.erb (0.8ms)
Completed 200 OK in 1454ms (Views: 1429.3ms | ActiveRecord: 3.1ms)
Started POST "/contact" for xx.xxx.xx.xxx at 2015-06-06 14:15:49 +0000
Processing by MessagesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zAxxxSKMYKey/jxmqqvxxxr***43g2Ud9r6SQ==", "message"=>{"name"=>"", "email"=>"", "content"=>""}, "commit"=>"Send"}
Rendered messages/new.html.erb within layouts/application (7.3ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (3.2ms)
Rendered layouts/_footer.html.erb (0.3ms)
Completed 200 OK in 849ms (Views: 844.9ms | ActiveRecord: 0.0ms)
答案 0 :(得分:1)
添加attr_accessor :name
等同于以下代码
def name
@name
end
def name=(val)
@name = val
end
因此,如果您的数据库中有一个名为name
的列,则不会编写该列。这就是这里发生的事情。由于您将这些列设置为null: false
,因此如果postgres为null
则会引发错误。