← back to the blog
fousa blog
Overwrite custom field errors in Rails3
When using form helpers in your form to display your textfield you always have to match your CSS style to match with the div's that are added by Ruby on rails when an error occurs.
This is the form helper:
f.text_field :titleThis is the generated tag with the error div surrounding it:
<div class="fieldWithErrors"> <input id="post_title" name="post[title]" size="30" type="text" value="" /> </div>Now I don't like this generation, so I followed Ryan bates's railscast on how to change this. And it works great! But for Rails 3 it gives me some weird output as a string.
So that is way I changed something in the implementation.
First of all I added the code snippet somewhere in an initializer which is much cleaner!
Second of all I had to add .html_safe. This makes sure that rails inserts the html into your code without changing it! If it's not safe, Rails would need to escape it and then you get the weird output... Here is a nice article concerning this.
Here is what the code looks after the modification.
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| "<div class=\"error\">#{html_tag}</div>".html_safe end
Send me some feedback!
