Reputation: 935
I am trying simple_form nested attributes as suggested in https://github.com/plataformatec/simple_form/wiki/Nested-Models
The thing is, when I render the form I just can see the submit button, but not the input field. What am I doing wrong?
_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
Upvotes: 0
Views: 753
Reputation: 4640
You need to add @incident.comments.build
to the show action of Admin::IncidentsController. Now it has no comments, I suppose, so the form is empty.
And you need to add :id
to comments_attributes
, without it comment can't be saved. If you planning to have some 'Delete' checkbox for existing comments you also need to add :_destroy
to the attributes array
Upvotes: 3