Ruby-on-rails 在不保存的情况下获取验证错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10995972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get validation error messages without saving
提问by brittohalloran
Post
:belongs_to :user
User
:has_many :posts
In my signup workflow they draft a Post first, then on the next page enter their User information to signup.
在我的注册工作流程中,他们首先起草帖子,然后在下一页输入他们的用户信息进行注册。
# intermediate step, validate that Post is valid before moving on to User creation
# posts_controller:
@post = Post.new(params[:post])
if @post.valid?
# go on to create User
else
render 'new'
end
BUT! @post error messages aren't created since I'm not saving the @post model I'm just checking for .valid?. How do I create the error messages without saving?
但!@post 错误消息没有被创建,因为我没有保存我只是检查的 @post 模型.valid?。如何在不保存的情况下创建错误消息?
回答by sohaibbbhatti
If I understand your question correctly you want to get the errors without saving the model?
如果我正确理解您的问题,您想在不保存模型的情况下获得错误吗?
That is exactly what is happening. @post.valid?
这正是正在发生的事情。 @post.valid?
will return true or false depending on whether there are any errors. If there are errors. they will be added to @post.errorshash.
将根据是否有任何错误返回 true 或 false。如果有错误。它们将被添加到@post.errors哈希中。
In the situation where you want to save just call @post.saveIt will return true if successfully saved or false if errors are present while populating @post.errorsin the process
在您想保存的情况下,只需调用@post.save它会在成功保存时返回 true,如果在填充@post.errors过程中出现错误则返回 false
回答by Romain
According to documentation, once you've called #valid?or #invalid?on a record, #errorsis populated.
根据文档,一旦你打电话#valid?或#invalid?记录,#errors就会填充。

