无法将文本区域样式更改为field_with_error

时间:2011-09-29 15:11:03

标签: ruby-on-rails forms

我正在处理这个用于创建新会话的传统表单。它有两个字段:名称和描述(对话的第一个评论)

以下是字段: _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? }

由于某种原因,proc与base.rb

错误的字段相关联
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }

不会调用文本区域,因此它不会更改其样式以使其变为红色。它适用于:name字段。错误消息正确显示

我错过了什么? 谢谢!

2 个答案:

答案 0 :(得分:1)

验证将针对Comment字段上的Conversation模型(而不是body模型)。检查以确保验证存在。您可以对其进行调试,以确保comment_fields.object字段上的body也设置了错误。

答案 1 :(得分:1)

我没有在代码中注意到这一行的一个重要部分:

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

您调用f.object.comments.build,这意味着您将始终以Comment的新实例结束(而不是在控制器中验证的实例)。

为避免这种情况,您可以在控制器中构建注释。如果您正在使用正常的restful操作,那么您可能有两个地方想要构建注释。第一个是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