Reputation: 2907
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) All errors have attribute prefixed: 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) Red highlights: 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!
Upvotes: 1
Views: 861
Reputation: 2341
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!
Upvotes: 1