2011-03-18 35 views
6

如何在不通過驗證時阻止Rails更改我的代碼。Rails將包含帶有錯誤的字段封裝爲div

每次軌道圍繞我場

<div class='field_with_error'>...</div> 

我可以編輯fields_with_error

.fields_with_error{ display: inline } 

其作品,但它是哈克

+0

有沒有嚴肅的方法來防止這種不捕捉它呢? – ohhh 2015-09-18 17:43:15

回答

7

它的罰款。使用CSS的東西,而不是這樣做。

 
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag| 
    "<span class='field_error'>#{html_tag}</span>" 
end 

這我覺得是更哈克:)

+0

它更hacky,真實:)但我希望有一個簡單的解決方案,就像關閉rails來更改我的代碼 – fl00r 2011-03-18 16:31:44

+0

rails如何「改變你的代碼」?如果rails包裝它,那麼你正在使用rails helper。如果你不需要,不要使用這些助手,或者編寫自己的表單生成器助手。 – DGM 2011-03-18 18:59:22

+0

我不使用它們。唯一我使用的是調用'@ object.errors' ... – fl00r 2011-03-18 20:57:30

5

我在environment.rb中使用。更hacky ;-)

# 
# Fix annoying <div class="fieldsWithError"> wrapping after validation 
# http://dev.rubyonrails.org/ticket/3587 
# 

ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| 
    msg = instance.error_message 

    if html_tag =~ /<(input|textarea|select)[>]+class=/ 
    class_attribute = html_tag =~ /class=['"]/ 
    html_tag.insert(class_attribute + 7, "error ") 
    elsif html_tag =~ /<(input|textarea|select)/ 
    first_whitespace = html_tag =~ /\s/ 
    html_tag[first_whitespace] = " class='error' " 
    end 

    html_tag 
} 
-1

您還可以使用jQuery來做到這一點。仍然感覺像一個黑客,但它的工作。

$('.field_with_errors input').unwrap(); 
+0

事實上,這可以在非常特殊的情況下提供幫助。謝謝! – pierrea 2014-10-22 14:23:40

+0

如果你有沒有運行JS的用戶,他們會有不同的行爲。對此使用JS是矯枉過正的。 – 2018-02-06 01:22:21

相關問題