ruby-on-rails - 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
解决方案
您需要添加@incident.comments.build
到 Admin::IncidentsController 的显示操作。现在它没有评论,我想,所以表格是空的。
而且你需要添加:id
到comments_attributes
,没有它评论不能被保存。如果您打算为现有评论添加一些“删除”复选框,您还需要添加:_destroy
到属性数组
推荐阅读
- angular - http调用后角度重定向到路由
- ios - 应用程序转到背景一段时间后,CoreGraphic 的视图绘制消失了
- linux - 如何打印包含句子的列而不丢失awk printf中第一个单词之后的所有内容?
- redux - Redux - 从数组中删除项目
- oracle - 如何在 Windows 桌面的 Oracle 中创建目录
- php - 为什么 php == 不能在工匠 tinker laravel 上工作
- node.js - 使用 Puppeteer 和 Node JS 进行 Sharepoint 身份验证
- javascript - 根据搜索参数使用 JSONPath 在 json 中搜索
- javascript - 如何将表单中的多个复选框字段分配给ajax请求
- ruby-on-rails - Shrine::Error: storage :cache 未在 FileUploader 上注册