2017-01-25 4 views
1

많은 검색을했는데 허용 된 속성에 ID를 모두 추가했지만 그 경우에는 작동하지 않습니다. 어떻게 여러 개의 빈 행을 방지 할 수 있습니까? 관련 테이블에서) 중첩 된 양식을 편집 할 때 생성되지 않습니까? 양식을 편집 할 때마다 비어있는 관련 레코드의 양이 두 배가됩니다.중첩 된 양식을 편집 할 때 중복을 작성하는 레일

컨트롤러 :

class EnquiriesController < ApplicationController 
    before_action :authenticate_user! 
    load_and_authorize_resource 
    # before_action :set_enquiry, only: [:show, :edit, :update, :destroy] 
    #11-1-2017 Devise geinstalleerd, nog verder afmaken!(oa onderstaande uncommenten) 


    # GET /enquiries 
    # GET /enquiries.json 
    def index 
    # @enquiries = Enquiry.all 
    @enquirie = current_user.enquiries 
    end 

    # GET /enquiries/1 
    # GET /enquiries/1.json 
    def show 
    end 

    # GET /enquiries/new 
    def new 
    @enquiry = Enquiry.new 
    @enquiry.enquirymeasures.build 
     #@enquiry.measurements.build 
    @enquiry.tools.build 
    @enquiry.build_applicant 
    @enquiry.signatures.build 
    @enquiry.gasmeters.build 
     #@enquiry.enquirymeasures.build.build_measurement 
    end 

    # GET /enquiries/1/edit 
    def edit 
    #nog op kunnen slaan!!!! 1-01-17 Marco 
    @enquiry = Enquiry.find(params[:id]) 
    @enquiry.enquirymeasures.build 

    @enquiry.tools.build 
    @enquiry.build_applicant 
    @enquiry.signatures.build 
    @enquiry.gasmeters.build 

    end 

    # POST /enquiries 
    # POST /enquiries.json 
    def create 
    @enquiry.user_id = current_user.id 
    @enquiry = Enquiry.new(enquiry_params) 
    #@enquiry.enquirymeasures.build 

    respond_to do |format| 
     if @enquiry.save 
     format.html { redirect_to @enquiry, notice: 'Enquiry was successfully created.' } 
     format.json { render :show, status: :created, location: @enquiry } 
     else 
     format.html { render :new } 
     format.json { render json: @enquiry.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    #approved_enquiry_notification 

    # PATCH/PUT /enquiries/1 
    # PATCH/PUT /enquiries/1.json 
    def update 
    @enquiry = Enquiry.find(params[:id]) 
    respond_to do |format| 
     if @enquiry.update(enquiry_params) 
     format.html { redirect_to @enquiry, notice: 'Enquiry was successfully updated.' } 
     format.json { render :show, status: :ok, location: @enquiry } 
     else 
     format.html { render :edit } 
     format.json { render json: @enquiry.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /enquiries/1 
    # DELETE /enquiries/1.json 
    def destroy 
    @enquiry.destroy 
    respond_to do |format| 
     format.html { redirect_to enquiries_url, notice: 'Enquiry was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 
    #25-1 MG alle attributes hadden ook :id 
    def enquiry_params 
     params.require(:enquiry).permit(:id, :reference, :location, :description, :date, :amount, :approved, enquirymeasures_attributes: [:id, :responsible, :done, :needed, :measurement_id, :user], 
             tools_attributes: [:id, :handtool, :other, :motorvehicle, :compressor, :ramp, :scaffold, :crane, :ladder, :generator, :tankladder], 
             applicant_attributes: [:id, :name, :email, :contractor_id], 
             signatures_attributes: [:id, :date, :signature, :representative_id], 
             gasmeters_attributes: [:id, :date, :tester, :signature, :oxigen, :o_needed, :o_continu, :explosives, :e_needed, :e_continu, :mat1, :mat1_needed, :mat1_continu, :mat2, :mat2_needed, :mat2_continu, :mat3, :mat3_needed, :mat3_continu], 
             controls_attributes: [:id, :enquirycheck, :workspacecheck, :enquiry_id]).merge(user_id: current_user.id) 


    end 



end 

모델 : 주 : 관련 모델의

class Enquiry < ActiveRecord::Base 
    has_many :enquirymeasures, dependent: :destroy 
    accepts_nested_attributes_for :enquirymeasures, :reject_if => lambda { |a| a[:responsible].blank? }, :allow_destroy => true 


    has_many :tools, dependent: :destroy 
    accepts_nested_attributes_for :tools 

    has_many :controls, dependent: :destroy 
    accepts_nested_attributes_for :controls 

    has_one :applicant, dependent: :destroy 
    accepts_nested_attributes_for :applicant 

    has_one :contractor, through: :applicant 

    has_many :signatures, dependent: :destroy 
    accepts_nested_attributes_for :signatures 
    has_many :representatives , through: :signatures, :source => :representatives 

    has_many :gasmeters, dependent: :destroy 
    accepts_nested_attributes_for :gasmeters 

    belongs_to :user 

    #voor de goedkeuring mail 
    after_create :send_confirmation_mail 
    def send_confirmation_mail 
    ModelMailer.new_enquiry_mail(self).deliver 
    end 

    #after_update :send_approved_mail 
    #def send_approved_mail 
    # if params[:approved] == '1' 
    # if :approved == '1' 
    # ModelMailer.enquiry_approved_mailer(self).deliver 
    # end 
    #end 

end 

하나

class Tool < ActiveRecord::Base 
    belongs_to :enquiry 
end 

내가 그것을 때문에 전체 _form을 포함하지 않았다 매우 길다 (300 라인). 그러나 당신에게 아이디어를주기 위해 :

,
<div class="form-group "> 

     <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> 

      <%= f.fields_for :applicant do |a| %> 

       <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> 
       <div class="panel panel-default"> 
        <div class="panel-heading" role="tab" id="headingOne"> 
        <h4 class="panel-title"> 
         <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> 
         Aanvraag 
         </a> 
        </h4> 
        </div> 
        <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"> 
        <div class="panel-body"> 
         <%= f.label :Referentie, :class => "col-sm-2 control-label" %> 
         <%= f.text_field :reference, :class => "form-control" %> <br> 

         <%= f.label :Locatie, :class => "col-sm-2 control-label" %> 
         <%= f.select :location, [['Chemiepark', 'chemiepark'], ['Winschoten', 'winschoten'], ['Farmsum', 'farmsum']], :class => "form-control" %> 
         <br> 
         <br> 

         <%= f.label :Omschrijving, :class => "col-sm-2 control-label" %> 
         <%= f.text_area :description, :class => "form-control" %> <br> 

         <%= f.label :Aantal_uitvoerenden, :class => "col-sm-2 control-label" %> 
         <%= f.number_field :amount, :class => "form-control" %> <br> 

         <%= f.label :Datum %><br> 
         <%= f.datetime_select :date %> <br> 

         <%= a.label :Aanvrager %><br> 
         <%= a.text_field :name %> <br> 

         <%= a.label :email %><br> 
         <%= a.text_field :email %> <br> 

         <%= a.label :Aannemer %><br> 
         <%= a.collection_select(:contractor_id, Contractor.all, :id, :name, prompt: true) %> 
        </div> 
        </div> 
       </div> 
       </div> 

      <% end %> 

답변

0

각 중첩 된 특성에 reject_if 절을 추가해야하며, 양식에서 중첩 된 특성을 자동으로 거부하지 않으려면 필수 필드에 대한 개별 모델 각각에 유효성 검사를 추가 할 수 있습니다. 당신이 요구 한대로 오류를 되돌릴 것입니다.

보조 노트에
has_many :tools, dependent: :destroy 
accepts_nested_attributes_for :tools, reject_if: :all_blank 

has_many :controls, dependent: :destroy 
accepts_nested_attributes_for :controls, reject_if: :all_blank 

has_one :applicant, dependent: :destroy 
accepts_nested_attributes_for :applicant, reject_if: :all_blank 

has_one :contractor, through: :applicant 

has_many :signatures, dependent: :destroy 
accepts_nested_attributes_for :signatures, reject_if: :all_blank 

has_many :representatives , through: :signatures, :source => :representatives 

has_many :gasmeters, dependent: :destroy 
accepts_nested_attributes_for :gasmeters, reject_if: :all_blank 

, 나는 중첩 된 형태로 작업 할 때 매우 도움이 될하기 위해 cocoon gem을 발견했습니다.

+0

감사합니다. 나는 당신의 해결책을 시험해 보았습니다. 그것은 거의 올바른 결과를주었습니다. 그래서 나는 그것을 조금 비틀었고 이제는 효과가있는 것 같습니다. all_blank를 다음과 같이 변경했습니다. reject_if => lambda {| a | a [: handtool]. 블랭크? }, : allow_destroy => 테이블 당 필수 필드를 사용합니다. 그래서 가스 계량기의 경우 [: 테스터] 등 감사합니다! – Marco

0

은 다음과 같이해야합니다 :

def update 
    @enquiry = Enquiry.find(params[:id]) 
    if @enquiry.update_attributes(enquiry_params) 
    # Handle a successful update. 
    else 
    render 'edit' 
end 

및 enquiry_params에서 ID를 제거합니다.

+0

every : id를 enquiry_params에서 제거 하시겠습니까? 그냥 with : the 메인 테이블에 대한 ID와 if @ enquiry.update_attributes (enquiry_params) 대신에 내가 가지고있는 것보다는 succes가 없는지 테스트했다. 그것은 여전히 ​​중첩 테이블 당 1 레코드를 추가합니다. – Marco

+0

중첩 된 매개 변수에서 ID를 허용하거나 기존 레코드를 업데이트하기 때문에 새 모델을 빌드 할 필요가 없습니다. 그래서 중첩 된 매개 변수에서 모든 ID를 제거하는 것이 도움이 될 것이라고 생각합니다. – trueinViso