简体   繁体   English

Rails:更改错误消息

[英]Rails: Changing Error Messages

My error messages are not showing automatically, so I decided to use flash as a workaround. 我的错误消息没有自动显示,因此我决定使用Flash作为解决方法。 This is what I'm doing 这就是我在做的

Controller: 控制器:

flash[:notice] = @post.errors.full_messages

View: 视图:

<%= flash[:notice] %>

Then, I get this ugly error message on my view. 然后,我在视图上收到了这个丑陋的错误消息。

["Content can't be blank", "Content is too short (minimum is 10 characters)"] 

But at least, the user successfully gets the error message. 但是至少,用户可以成功获取错误消息。 Now I need to customize the error message and make it look a little bit more pretty. 现在,我需要自定义错误消息,并使它看起来更漂亮。 I guess I could parse each error sentence into some local variables and show them (is there a more sophisticated way?). 我想我可以将每个错误语句解析为一些局部变量并显示出来(是否有更复杂的方法?)。 However, I don't know how to customize the error message. 但是,我不知道如何自定义错误消息。 For example, "Content can't be blank" should be changed to "You left the content blank". 例如,“内容不能为空”应更改为“您将内容留为空白”。 Where can I fix this? 我在哪里可以解决这个问题?

What happens is that when @post contains some validation errors doing @post.errors.full_messages returns an array of errors that happened during validation. 发生的是,当@post包含一些验证错误时, @post.errors.full_messages返回验证期间发生的一系列错误。

To display them nicely you might want to do something like 为了很好地显示它们,您可能想要做类似的事情

<%- flash[:notice].each do |error| %>
  <%= error %>
<% end %>

EDIT Whoops I misread the question. 编辑糟糕,我读错了问题。

These errors are validation errors in your model where you have the validations like 这些错误是模型中的验证错误,您可以在其中进行如下验证

validates you can pass custom messages like so validates您可以像这样传递自定义消息

validates :content, :presence => { :message => "You left the content blank" }

Update : check this link out for the options you have 更新 :检查此链接以了解您拥有的选项

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM