programing tip

RoR 중첩 속성은 편집시 중복을 생성합니다.

itbloger 2020. 11. 23. 07:53
반응형

RoR 중첩 속성은 편집시 중복을 생성합니다.


Ryan Bates RailsCast # 196 : Nested model form part 1 을 따르려고합니다 . Ryans 버전에는 두 가지 명백한 차이점이 있습니다. 1) 빌트인 스캐 폴딩을 사용하고 있지만 그가 사용하는 것처럼 멋지지 않습니다 .2) 레일을 실행하고 있습니다. ,하지만 4가 아닙니다).

그래서 내가 한 일은

rails new survey2
cd survey2
bundle install
rails generate scaffold survey name:string
rake db:migrate
rails generate model question survey_id:integer content:text
rake db:migrate

그런 다음 모델에 연결을 추가했습니다.

class Question < ActiveRecord::Base
  belongs_to :survey
end

그래서

class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

그런 다음 중첩 된 뷰 부분을 추가했습니다.

<%= form_for(@survey) do |f| %>
  <!-- Standard rails 4 view stuff -->

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.fields_for :questions do |builder| %>
      <div>
        <%= builder.label :content, "Question" %><br/>
        <%= builder.text_area :content, :rows => 3 %>
      </div>
    <% end %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

마지막으로 컨트롤러는 새 설문 조사가 인스턴스화 될 때마다 3 개의 질문이 생성되도록합니다.

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

  # Standard rails 4 index and show 

  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times { @survey.questions.build }
    Rails.logger.debug("New method executed")
  end

  # GET /surveys/1/edit
  def edit
  end

  # Standard rails 4 create

  # PATCH/PUT /surveys/1
  # PATCH/PUT /surveys/1.json
  def update
    respond_to do |format|
      if @survey.update(survey_params)
        format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @survey.errors, status: :unprocessable_entity }
      end
    end
  end

  # Standard rails 4 destroy

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_survey
      @survey = Survey.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, questions_attributes: [:content])
    end
end

So, creating a new survey with three questions is fine. However, if I try to edit one of the surveys, the original three questions are maintained, while an additional three more are created. So instead of having 3 questions for the edited survey, I now have 6. I added

Rails.logger.debug("New method executed")

to the new method in the controller, and as far as I can tell, it is not executed when I'm doing an edit operation. Can anyone tell me what I'm doing wrong?

Any help is greatly appreciated!


So I figured it out. I had to add :id to the permitted params in the survey_params method. It now looks like this:

# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:id, :content])
end

which works perfectly. I'm a RoR newbie, so please take my analysis of this with a grain of salt, but I guess that new id's where generated instead of being passed to the update action. Hope this helps someone else out there.


Using cocoon gem on Rails 4, I was still getting duplicate fields even after adding :id to the permitted list when editing. Noticed the following as well

Unpermitted parameters: _destroy
Unpermitted parameters: _destroy

So I added the :_destroy field to the permitted model_attributes: field and things worked smoothly after that.

For example...

def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:id, :content, :_destroy])
end

참고URL : https://stackoverflow.com/questions/18946479/ror-nested-attributes-produces-duplicates-when-edit

반응형