简体   繁体   中英

Rails - Editing default appearance of error messages

New to rails, and I'm doing some simple exercises. Now I'm playing around with error messages. I have a few questions concerning the default behavior of these

1) Why are all error messages prefixed with the variable that cases the validation error? 为什么所有错误消息都带有用于验证错误的变量前缀? In this case it's 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) : Why is the "Score" label and the corresponding input field outlined in red. :为什么“得分”标签和相应的输入字段以红色According to the _form.html.erb file, they are <div class="field"> so I don't understand where this red outline is coming from. Is there a way to change this?

Thanks!

错误信息

Welcome to 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 . You should have a file in there called 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.

@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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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