simple_form不显示嵌套字段

时间:2018-05-09 02:43:18

标签: ruby-on-rails simple-form nested-attributes

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

中建议的simple_form嵌套属性

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

Screen with input field missing

_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

1 个答案:

答案 0 :(得分:2)

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

您需要将:id添加到comments_attributes,如果没有,则无法保存评论。如果您计划删除一些&#39;删除&#39;现有注释的复选框,您还需要将:_destroy添加到属性数组