为嵌套关联呈现的html标签未包装在field_with_errors div中

时间:2019-05-10 19:43:17

标签: ruby-on-rails bootstrap-4 ruby-on-rails-5

Rails 5.1.4,ruby:2.3.7

对于父模型和子模型,我有一个嵌套的表单,并在父模型的范围内验证了子模型中标签的唯一性。问题是,当我在两个表单中提交具有相同名称的表单时,没有一个被包裹在field_with_errors类中。我需要将html标签包装在该类中,以便随后可以使用bootstrap 4 invalid-feedback和无效的CSS类在表单上呈现错误。

如何使用field_with_errors div包裹了dashboard_label的text_field来呈现表单?

模型如下:

class Project < ApplicationRecord
  has_many :study_media_files
end

class StudyMediaFile < ApplicationRecord
  belongs_to :project
  validates :dashboard_label, uniqueness: { scope: :project } 
end

控制器代码如下:

class DsasController < ApplicationController
  def show
    @project = Mrcore::Project.find params[:id]
  end

  def update
    @project = Mrcore::Project.find params[:id]
    if(@project.update project_params)
      redirect_to @project, notice: 'updated successfully'
    else
      render 'show'
    end
  end

  private

  def project_params
    params.require(:project).permit(study_media_files_attributes: %i[id dashboard_label show])
  end
end

视图:

<%= f.fields_for :study_media_files, @project.study_media_files.non_zero_duration do |media_form| %>
    <div class="row ">
        <div class="col-4 small">
            <%= media_form.object.affdex_movie_id %>
        </div>
        <div class="col-5">
            <%= media_form.text_field :dashboard_label, class: 'input-sm col-lg form-control', required: true %>
        </div>
        <div class="col-2 float-right">
            <%= media_form.check_box :show, { class: 'form-check-input ml-2' } %>
        </div>
    </div>
<% end %>

似乎出于某种原因,对象的dashboard_label被重置为其原始值。

1 个答案:

答案 0 :(得分:0)

问题是带有功能字段的视图从数据库加载了数据,我猜想并使用下面的视图代码中的条件解决了覆盖项目对象上瞬态错误的问题。

<%= f.fields_for :study_media_files do |media_form| %>
    <% if media_form.object.duration > 0 %>
        <div class="row ">
            <div class="col-4 small">
                <%= media_form.object.affdex_movie_id %>
            </div>
            <div class="col-5">
                <%= media_form.text_field :dashboard_label, class: 'input-sm col-lg form-control' %>
            </div>
            <div class="col-2 float-right">
                <%= media_form.check_box :show, { class: 'form-check-input ml-2' } %>
            </div>
        </div>
    <% end %>
<% end %>

基本上将fields_for块上的集合移动到该块内的条件。