3
다음은 RailsCast # 196Nested Model Form Part 1
입니다. 모델과 컨트롤러의 이름이 같으며 모든 속성이 있습니다. 하지만 지금 편집을 시도하고 질문을 제거하려고 할 때. 체크 박스를 선택하면 질문이 삭제되지 않습니다. 모델 :중첩 모델 양식 레일 4에서 레코드 삭제 문제
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda {|a| a[:content].blank?} , :allow_destroy => true
end
class Question < ActiveRecord::Base
belongs_to :survey
end
조사 컨트롤러 :
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
def index
@surveys = Survey.all
end
def show
end
def new
@survey = Survey.new
3.times {@survey.questions.build}
end
def edit
end
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render :show, status: :created, location: @survey }
else
format.html { render :new }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def update
#abort params[:survey][:questions_attributes].inspect
respond_to do |format|
if @survey.update(survey_params)
format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
format.json { render :show, status: :ok, location: @survey }
else
format.html { render :edit }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def destroy
@survey.destroy
respond_to do |format|
format.html { redirect_to surveys_url, notice: 'Survey was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_survey
@survey = Survey.find(params[:id])
end
def survey_params
params.require(:survey).permit(:name, questions_attributes: [ :id, :content ])
end
end
파일보기
<%= form_for(@survey) do |f| %>
<% if @survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% @survey.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.fields_for :questions do |builder| %>
<div class="field">
<%= builder.label :content, 'Question' %><br>
<%= builder.text_area :content, :rows=>3 %><br>
<%= builder.check_box :_destroy %>
<%= builder.label :_destroy, "Remove Question" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
01 이와 같이
그리고 나는 중단을위한 업데이트 방법에 주석을 달았습니다. 그렇게하면 내가 중단한다
{"0"=>{"content"=>"SEM 1", "_destroy"=>"0", "id"=>"4"}, "1"=>{"content"=>"Sem 2", "_destroy"=>"0", "id"=>"5"}, "2"=>{"content"=>"Sem 3", "_destroy"=>"1", "id"=>"6"}}
나는 실수를 저질렀다. 나를 안내 해줘. 미리 감사드립니다.
SOOO 바보 정의 라인에
에allow_destroy: true
을, 당신이해야 할, 또한 허용 PARAMS:_destroy
를 추가합니다. 고마워. 이제는 작품입니다. :) –@HetalKhunti, 속임수가 맞으면 대답을 받아 들여주세요. –
예. 시도했지만 6 분 후에 받아 들일 수 있다고 말합니다. 나는 확실히 할 것입니다. 내가 11 명 밖에 없기 때문에 미안해. 그것을 위해 min.15 담당자가 필요합니다. –