simple_form 不显示某一特定表单的验证错误
这是我的表单:
= simple_form_for [@post, @comment] do |f|
= f.input :text, :label => false
= f.button :submit
评论嵌套在帖子资源中。评论验证: 验证 :text, :length => {:最小值=> 5 }
评论控制器:
def create
@post = Post.find params[:game_id]
comment = @post.comments.build :user_id => current_user, :text => params[:comment][:text]
comment.save
redirect_to @post
end
表单本身工作正常。如果我输入超过 5 个字符,则会创建评论。但如果它更少,我就会被重定向到 posts#show
并且表单中没有验证错误(我已经检查了来源)。
我还尝试填写设备注册表,如果失败,我可以看到错误。
我猜问题是由重定向引起的。但无论如何,我不知道如何解决它。
Here's my form:
= simple_form_for [@post, @comment] do |f|
= f.input :text, :label => false
= f.button :submit
Comments are nested within Posts resources. Comments validation: validates :text, :length => { :minimum => 5 }
Comments controller:
def create
@post = Post.find params[:game_id]
comment = @post.comments.build :user_id => current_user, :text => params[:comment][:text]
comment.save
redirect_to @post
end
The form itself works fine. If I enter more than 5 chars, the comment gets created. But if it's less, I just get redirected to posts#show
and there are no validation errors in the form (I've checked the sources).
I also tried filling the devise registration form, and if it fails, I can see the errors.
I guess the problem is caused by the redirect. But anyways, I don't know how to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您重定向用户,错误就会丢失,除非您的应用程序以某种方式记住它们。有两种可能性可以解决此问题:
不重定向用户,而只是使用
render
显示带有错误消息的视图。例如,这就是 Devise 所做的事情。确实重定向用户,但以某种方式传递错误消息。有很多方法可以做到这一点,例如将它们保存为简单的字符串,或者以某种序列化的形式保存在闪存中。但这通常比较复杂,并且只有在需要重定向时才应该这样做。
If you redirect the user, the errors are lost unless your application remembers them somehow. There are two possibilities to solve this problem:
Don't redirect the user, but just use
render
to display the view with error messages. That's what Devise does, for example.Do redirect the user, but transfer along the error messages somehow. There are many ways to do this, for example by saving them, either as a simple string, or in some serialized form, in the flash. But this is usually more complicated and should only be done if the redirect is necessary.