Rails不会为使用fields_for创建的字段添加“field_with_errors”包装器

时间:2015-06-23 20:37:12

标签: ruby-on-rails forms activemodel

我想要做的是通过将其传递给fields_for来命名一个以动态构建的形式定制的对象。该对象不是ActiveRecord模型,我正在尽最大努力使其尽可能轻松地使用它。

除了没有添加的“field_with_errors”包装器之外,一切都有效。关于如何使这部分工作的任何想法?

我有一个表单,它将数据提交给FormResponses模型并运行其验证。运行验证后,[1] pry(#<#<Class:0x007fe743c64418>>)> form_response => #<FormResponse:0x007fe74d30aa98 id: nil, data: {"name_prefix"=>"Mr.", "first_name"=>"", "middle_initial"=>"", "last_name"=>"", "name_suffix"=>"", "title"=>""}, form_id: 2, created_at: nil, updated_at: nil> [2] pry(#<#<Class:0x007fe743c64418>>)> form_response.errors => #<ActiveModel::Errors:0x007fe74d309080 @base= #<FormResponse:0x007fe74d30aa98 id: nil, data: {"name_prefix"=>"Mr.", "first_name"=>"", "middle_initial"=>"", "last_name"=>"", "name_suffix"=>"", "title"=>""}, form_id: 2, created_at: nil, updated_at: nil>, @messages={:will_attend=>["Please indicate your attendance"], :first_name=>["Please provide your first name"]}> # this is what I pass to the form_for builder [3] pry(#<#<Class:0x007fe743c64418>>)> form_response.form_data => #<OpenStruct name_prefix="Mr.", first_name="", middle_initial="", last_name="", name_suffix="", title=""> 对象包含命名空间的表单数据以及错误:

= form_for form_response, url: "", authenticity_token: false, html: {class: "form"} do |ff|
  = hidden_field_tag "authenticity_token", csrf_token
  = ff.hidden_field "_prefilled_status", value: is_prefilled.prefilled
  = ff.hidden_field "_prefilled_condition", value: is_prefilled.condition

  = fields_for :form_data, form_response.form_data do |f|
    = ff.hidden_field "form_id", value:  form_response.form_id
    # form_components holds the form field tree data which lets us create the form dynamically
    - form_components.each do |component|      
      = render partial: "./#{component.kind}", locals: { f: f, component: component }

我以下列方式显示此对象:

form.html.slim

li class=component.container_css
  = f.label component.field_name, component.label, class: concat_and_trim('desc', component.required_class)
  span = f.text_field component.field_name, component.tag_options_with_css

使每个字段由对应于字段类型的部分字段处理,例如:

_text.html.slim

  = fields_for :form_data, form_response.form_data do |f| 

问题是,当出现错误时,使用f.field_name创建的字段不会获得“field_with_errors”包装。

鉴于错误发生在传递给“ff”表单构建器的form_response活动记录模型上,它们不应该触发form_for对象的包装吗?

如果我包含form_response.form_data,其中包含在form_data命名空间下提交的表单字段值,则form_for字段会保留提交的值,如下所示:

  = fields_for :form_data do |f|

如果省略form_response.form_data部分,则会在提交

时清除字段
{{1}}

这意味着fields_for使用该信息预填充字段。如何将错误信息传递给fields_for,以便字段获取错误类包装?

0 个答案:

没有答案