简体   繁体   English

Rails-编辑错误消息的默认外观

[英]Rails - Editing default appearance of error messages

New to rails, and I'm doing some simple exercises. Rails的新手,我正在做一些简单的练习。 Now I'm playing around with error messages. 现在,我正在处理错误消息。 I have a few questions concerning the default behavior of these 我有一些关于这些默认行为的问题

1) All errors have attribute prefixed: Why are all error messages prefixed with the variable that cases the validation error? 1) 所有错误的属性都带有前缀:为什么所有错误消息都带有用于验证错误的变量前缀? In this case it's score . 在这种情况下,它是score How can I remove this attribute name from the error message, and just display my error message? 如何从错误消息中删除此属性名称,而仅显示我的错误消息? There's gotta be an easy way to do this? 有没有简单的方法可以做到这一点?

2) Red highlights : Why is the "Score" label and the corresponding input field outlined in red. 2) 红色突出显示 :为什么“得分”标签和相应的输入字段以红色突出显示 According to the _form.html.erb file, they are <div class="field"> so I don't understand where this red outline is coming from. 根据_form.html.erb文件,它们是<div class="field">所以我不知道这个红色轮廓来自何处。 Is there a way to change this? 有办法改变吗?

Thanks! 谢谢!

错误信息

Welcome to Rails! 欢迎来到Rails! First off, you're using the default scaffolding. 首先,您正在使用默认脚手架。 If you're in rails 3.2+ then your styles will be located in /app/assets/stylesheets . 如果您使用的是Rails 3.2+,则您的样式将位于/app/assets/stylesheets You should have a file in there called scaffold.css.scss . 您应该在那里有一个名为scaffold.css.scss的文件。 This file is what is styling the red on the page. 该文件是页面红色的样式。

Now as for the markup, You have control over how these message are displayed. 现在,对于标记,您可以控制这些消息的显示方式。 When an object is saved, but validation fails, the object will have an errors object. 保存对象但验证失败后,该对象将具有errors对象。

@car = Car.new(params[:car])
@car.save #=> false
@car.errors.messages #=> {:make => "can't be blank", :model => "doesn't make sense"}

As you can see, the messages method on this errors object will return a hash where the keys are the attributes that failed validation, and the values are the string messages from your validations. 如您所见,此错误对象上的messages方法将返回一个哈希,其中键是验证失败的属性,而值是验证中的字符串消息。

These validations are set in your model, and can be fully customized by you. 这些验证是在您的模型中设置的,可以完全由您自定义。

class Car
    validates :make, presence: true
    validates :model, presence: true, message: "doesn't make sense"
end

So in your views you could easily do something like 因此,在您看来,您可以轻松地执行以下操作

<% if @car.errors.any? %>
   <% @car.errors.messages.each do |field, message| %>
       <!-- your custom html here -->
    <% end %>
<% end %>

So hope this helps! 因此希望这会有所帮助!

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

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