首页 > 解决方案 > simple_form 不显示嵌套字段

问题描述

我正在尝试https://github.com/plataformatec/simple_form/wiki/Nested-Models中建议的 simple_form 嵌套属性

问题是,当我呈现表单时,我只能看到提交按钮,但看不到输入字段。我究竟做错了什么?

缺少输入字段的屏幕

_form.html.erb

<%= simple_form_for [:admin, @incident] do |f| %>
  <%= f.error_notification %>

  <%= f.simple_fields_for :comments do |builder| %>
      <%= builder.input :info, label: "Informe de seguimiento" %>
  <% end %>


  <div class="form-actions">
    <%= f.submit "Enviar", class: "btn btn-primary" %>
  </div>
<% end %>

事件控制器.rb

class Admin::IncidentsController < ApplicationController
  before_action :set_incident, only: [:show, :edit, :update]
  def index
    @incidents = Incident.all
  end
  def show

  end
  def new
    @incident = Incident.new
    @incident.comments.build
  end
  def edit

  end

  def update
    respond_to do |format|
      if @incident.update(incident_params)
        format.html { redirect_to @incident, notice: 'Incidencia actualizada actualizada con éxito.' }
        format.json { render :show, status: :ok, location: @incident }
      else
        format.html { render :edit }
        format.json { render json: @incident.errors, status: :unprocessable_entity }
      end
    end
  end

  private
  def set_incident
    @incident = Incident.find(params[:id])
  end

  def incident_params
    params.require(:incident).permit(:info, :subject, :status, comments_attributes: [:info])
  end

end

事件.rb

class Incident < ApplicationRecord
  belongs_to :user, optional: true
  has_many :comments, dependent: :destroy
  accepts_nested_attributes_for :comments, allow_destroy: true, reject_if: proc { |attributes| attributes['info'].blank? }

  enum status: [:abierto, :tramite, :pendiente, :cerrado]
  after_initialize :set_default_status, :if => :new_record?

  def set_default_status
    self.status ||= :abierto
  end
end

评论.rb

class Comment < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :incident
end

标签: ruby-on-railssimple-formnested-attributes

解决方案


您需要添加@incident.comments.build到 Admin::IncidentsController 的显示操作。现在它没有评论,我想,所以表格是空的。

而且你需要添加:idcomments_attributes,没有它评论不能被保存。如果您打算为现有评论添加一些“删除”复选框,您还需要添加:_destroy到属性数组


推荐阅读