simple_form 未显示嵌套字段

simple_form not showing nested field

我正在尝试 simple_form https://github.com/plataformatec/simple_form/wiki/Nested-Models

中建议的嵌套属性

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

_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 %>

incidents_controller.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

incident.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

comment.rb

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

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

并且comments_attributes需要加上:id,否则评论无法保存。如果您计划为现有评论添加一些 'Delete' 复选框,您还需要将 :_destroy 添加到属性数组