问题
So I have an input element like this. The wrapping element is about, you know, a visual thing.
<div class="input-wrap">
<input class="blah-blah" />
</div>
When the <input>
contains the error, it'll be like this:
<div class="input-wrap">
<div class="field-with-errors">
<input class="blah-blah" />
</div>
</div>
But what I want to do is:
<div class="input-wrap field-with-errors">
<input class="blah-blah" />
</div>
I found this page, it's very close to my question
Rails 3: "field-with-errors" wrapper changes the page appearance. How to avoid this?
Now I know I can throw
config.action_view.field_error_proc = Proc.new { |html_tag, instance|
"#{html_tag}".html_safe
}
to avoid making a wrapping tag around the <input>
tag that has an error on. But what I really wanna do is, again, adding "field-with-errors" class on the direct parent of the <input>
tag. Can I do that? Does ActionView hold the tree structure of DOM Nodes?
回答1:
You can put the code for handling errors wherever you like, just call it as a block on the instance variable, for example
if @instance.errors.any?
<div class="field with errors">
@instance.errors.full_messages.each do |msg|
<p><%= msg %></p>
end
end
If you user this a lot, it's good to pull it out into a helper and pass in the instance variable as a parameter.
来源:https://stackoverflow.com/questions/15627809/can-field-with-errors-be-attached-to-the-parent-of-the-input-tag-that-raises-t