2011-09-29 48 views
0

我正在處理創建新對話的傳統表單。它有兩個字段:名稱和描述(對話的第一個評論)無法將文本區域樣式更改爲field_with_error

這裏是字段: _fields.haml

.conversation_title= f.label :name, t('.name') 
.clear 
= f.text_field :name, :style => 'width: 230px' 
= errors_for f.object, :name 

if f.object.new_record? 
    = f.fields_for :comments, f.object.comments.build do |comment_fields| 
    .conversation_title= comment_fields.label :description, t('.description') 
    = comment_fields.text_area :body, :placeholder => t("comments.new.conversation"), :style => 'width: 545px' 
    = errors_for f.object, :comments 

new視圖對話

= form_for [@current_project, @conversation], :html => { 'data-project-id' => @current_project.id, :name => 'form_new_conversation', :multipart => true } do |f| #, :onsubmit => 'return validate_form_new_conversation(form_new_conversation)' 
    = render 'fields', :f => f, :project => @current_project 
    = render 'watcher_fields', :f => f, :project => @current_project 

相關的驗證是:

conversation.rb

validates_presence_of :name, :message => :no_title, :unless => :simple? 
validates_presence_of :comments, :message => :must_have_one, :unless => :is_importing 

comment.rb

validates_presence_of :body, :unless => lambda { |c| c.task_comment? or c.uploads.to_a.any? or c.google_docs.any? } 

出於某種原因,從base.rb

@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe } 

相關聯的錯誤領域PROC不會被調用爲文本區,所以它不會改變它的風格讓它變成紅色。它適用於:name字段。錯誤信息得到正確顯示

我錯過了什麼? 謝謝!

回答

1

該驗證將針對body字段中的Comment模型(而不是Conversation模型)進行驗證。檢查以確保驗證存在。您可以進行調試以確保comment_fields.object也在body字段上設置了錯誤。

+0

我在我的問題的描述中添加了'Comment'model驗證。在調試時,顯然comment_fields.object沒有錯誤。因此,在評論主體字段下顯示的消息對應於對話的驗證。調試還顯示,多次調用相同的驗證。這是正常的嗎? – Arthur

+0

@arthur如果在嵌套表單的情況下多次觸發驗證,我不會感到驚訝。我會盡量避免它,但這不會是我最關心的問題。另外,我懷疑這是造成任何問題的原因。 –

1

我沒有注意到這行代碼中的一個重要組成部分:

= f.fields_for :comments, f.object.comments.build do |comment_fields| 

你叫f.object.comments.build這意味着你將永遠與Comment一個新實例(而不是被確認的情況下結束了在控制器中)。

要避免這種情況,您可以在控制器中創建註釋。如果您正在使用正常的寧靜行爲,那麼您可能有兩處要建立評論的地方。首先在new動作中,然後在create動作中。

def new 
    @conversation = Conversation.new 
    @conversation.comments.build # Create a blank comment so that the fields will be shown on the form 
end 

def create 
    @conversation = Conversation.new(params[:conversation]) 
    respond_to do |format| 
    if @conversation.save 
     format.html { redirect_to conversations_path } 
    else 
     format.html { 
     @conversation.comments.build if @conversation.comments.blank? # Create a blank comment only if none exists 
     render :action => "new" 
     } 
    end 
    end 
end 
+0

刪除f.object.comments.build並使對話控制器中內置的註釋使錯誤「無主題」和「無身體」同時出現,而它們只會在一次之前出現。儘管驗證,儘管評論的主體字段仍然沒有錯誤。 – Arthur

+0

@arthur在我看來,如果兩個錯誤都存在,那麼主體和主體錯誤都會顯示出來。我對遺漏的評論主體錯誤感到困惑。你說一個「沒有身體」的錯誤消息顯示,這聽起來像錯誤確實存在。我必須錯過重要的事情。 –