2017-03-13 6 views
1

Wicked 다중 단계 양식의 Gem in Rails에서 Cocoon gem을 사용하는 것과 관련된 비슷한 질문이 있습니다. has_many 연관이있을 때 양식을 잘 저장하지만 has_one 연관 (Client has_one doctor)이있을 때 레코드가 저장 한 다음 삭제하는 것처럼 보입니다. 이걸 알아 내려고 너무 오래 기다렸지 만 왜 그런 일이 벌어지는 지 알 수 없습니다.Wicked Gem - Rails를 사용하여 저장/업데이트시 Cocoon has_one 연관이 깨졌습니다.

class QuotesController < ApplicationController 
include Wicked::Wizard 
before_action :set_client, only: [:show, :update, :quote_success] 
steps :profile, :employment, :general_questions, :indemnity_details, :declarations 

def show 
    @client.build_doctor 
    @client.old_insurers.build 
    @client.practice_addresses.build 
    render_wizard 
end 

def update 
    @client.update(client_params) 
    render_wizard @client 
end 

def quote_success; end 

private 

def set_client 
    current_user = Client.find_by_id(session[:current_user_id]) 
    @client = current_user 
end 

def finish_wizard_path 
    if @client.valid? 
     ClientMailer.new_quote(@client).deliver 
     ClientMailer.new_quote_user_message(@client).deliver 
     end 
     quote_success_path 
    end 
end 

def client_params 
    params.require(:client).permit(:name, :email, :email_confirmation, :phone, :date_required, 
            :title, :first_name, :last_name, :date_of_birth, :nationality, :reg_body, 
            practice_addresses_attributes: [:id, :pa_line1, :pa_line2, :pa_line3, :pa_town, :pa_county, :pa_postcode, :other_practices, :_destroy], 
            old_insurers_attributes: [:id, :insurer, :oi_to, :oi_from, :oi_limit, :oi_excess, :oi_premium, :_destroy], 
            doctor_attributes: [:id, :gp_locum, :gp_locum_sessions, :gp_locum_locations]) 
    end 
    end 

클라이언트 모델 :

class Client < ActiveRecord::Base 
has_one :doctor, dependent: :destroy 
has_many :practice_addresses, dependent: :destroy 
has_many :callbks, inverse_of: :client 
has_many :old_insurers, dependent: :destroy 
accepts_nested_attributes_for :doctor 
accepts_nested_attributes_for :old_insurers, reject_if: :all_blank, allow_destroy: true 
accepts_nested_attributes_for :callbks 
accepts_nested_attributes_for :practice_addresses, reject_if: :all_blank, allow_destroy: true 
end 

의사 모델 : 문제

class Doctor < ActiveRecord::Base 
    belongs_to :client 
end 

보기 부분 :

<%= simple_form_for @client, url: wizard_path do |f| %> 

<%= yield f %> 
.... 

<div id="doctors"> 
    <%= f.simple_fields_for :doctor do |gp| %> 
    <%= render 'doctor_fields', f: gp %> 
    <% end %> 
</div> 

Doctor_fields :

<div class="nested-fields"> 
<div class="panel panel-default"> 
    <div class="panel-heading"> 
     <strong>General Questions - GP</strong> 
    </div> 
    <div class="panel-body"> 

     <div class="table-responsive"> 
      <div class=bs-example data-example-id=striped-table> 
       <table class="table table-striped"> 
        <thead> 
         <tr> 
          <th>Are you a:</th> 
          <th>Yes/No</th> 
          <th>Number of Sessions per week</th> 
          <th>Number of Locations</th> 
         </tr> 
         <tr> 
          <td>Locum</td> 
          <td><%= f.input :gp_locum, as: :radio_buttons, checked: false, label: false %></td> 
          <td><%= f.input :gp_locum_sessions, label: false, required: false %></td> 
          <td><%= f.input :gp_locum_locations, label: false, required: false %></td> 
         </tr> 
      </div> 
    </table> 
</div> 
</div> 

로그 :

Started GET "/quotes/employment" for ::1 at 2017-03-13 10:27:07 -0300 
Processing by QuotesController#show as HTML 
    Parameters: {"id"=>"employment"} 
    Client Load (1.6ms) SELECT "clients".* FROM "clients" WHERE   "clients"."id" = $1 LIMIT 1 [["id", 47]] 
    Doctor Load (1.1ms) SELECT "doctors".* FROM "doctors" WHERE "doctors"."client_id" = $1 LIMIT 1 [["client_id", 47]] 
    Rendered layouts/_quote_page_start.html.erb (2.0ms) 
    Rendered quotes/_doctor_fields.html.erb (234.4ms) 
    Rendered quotes/_form.html.erb (364.0ms) 
    Rendered layouts/_quote_page_mobile.html.erb (0.2ms) 
    Rendered quotes/employment.html.erb within layouts/application (423.2ms) 
    Rendered layouts/_shim.html.erb (0.1ms) 
    Profession Load (1.7ms) SELECT "professions".* FROM "professions" ORDER BY name ASC 
    Rendered layouts/_header.html.erb (8.6ms) 
    Rendered layouts/_footer.html.erb (11.4ms) 
Completed 200 OK in 1920ms (Views: 1845.1ms | ActiveRecord: 13.7ms) 


Started PATCH "/quotes/employment" for ::1 at 2017-03-13 10:27:21 -0300 
Processing by QuotesController#update as HTML 
    Parameters: {"utf8"=>"✓",  "authenticity_token"=>"7xvqW6SpbBgKy62zfdPclexYD9cxqNR/F8p+twW87F/vSz/5kmpRMCE59 LcL4taIclWj4ZeVQ6CRasqqy38iNw==", "client"=>{"profession_area"=>"General  Practicioner", "profession_area_other"=>"das", "doctor_attributes"=> {"gp_locum"=>"false", "gp_locum_sessions"=>"212", "gp_locum_locations"=>"21"},  "commit"=>"Next", "id"=>"employment"} 
    Client Load (2.0ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT 1 [["id", 47]] 
    (0.2ms) BEGIN 
     Doctor Load (0.5ms) SELECT "doctors".* FROM "doctors" WHERE  "doctors"."client_id" = $1 LIMIT 1 [["client_id", 47]] 
    SQL (0.6ms) INSERT INTO "doctors" ("gp_locum", "gp_locum_sessions", "gp_locum_locations", "client_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35) RETURNING "id" [["gp_locum", "f"], ["gp_locum_sessions", 212], ["gp_locum_locations", 21], ["client_id", 47], ["created_at", "2017-03-13 13:27:21.111656"], ["updated_at", "2017-03-13 13:27:21.111656"]] 
    (0.7ms) COMMIT 
    (0.7ms) BEGIN 
    (0.4ms) COMMIT 
Redirected to http://localhost:3000/quotes/general_questions 
Completed 302 Found in 38ms (ActiveRecord: 5.1ms) 


Started GET "/quotes/general_questions" for ::1 at 2017-03-13 10:27:21 -0300 
Processing by QuotesController#show as HTML 
    Parameters: {"id"=>"general_questions"} 
    Client Load (0.9ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT 1 [["id", 47]] 
    Doctor Load (0.4ms) SELECT "doctors".* FROM "doctors" WHERE "doctors"."client_id" = $1 LIMIT 1 [["client_id", 47]] 
    (0.1ms) BEGIN 
    SQL (0.8ms) DELETE FROM "doctors" WHERE "doctors"."id" = $1 [["id", 29]] 
    (0.5ms) COMMIT 

어떤 도움도 큰 감사 것입니다! 필요한 것이 있으면 알려주세요.

답변

2

[참고 : link_to_add_association 및 has_one에 대한 일반적인 발언]

link_to_add_association이 협회에 새 항목을 구축하려고합니다. has_one 관계가있는 경우 이는 효과적으로 기존의 관계를 대체한다는 의미입니다.

당신이 정말 link_to_add_association해야하는 경우는 다음과 같은 시도 할 수 있습니다 :

= link_to_add_association 'add doctor', @form_obj, :doctor, force_non_association_create: true 

(이 새로운 의사를 구축하지만, 연결을 사용하지 않는,이 복사되지 협회에 정의 된 일부 기본값을 의미 할 수 있습니다

) 형태의 저장 그래서 후 선택하지 않는하지만 기존의 의사는 덮어 쓰지 않습니다 [UPDATE : 귀하의 경우]

는 그냥 show 방법에서 @client.build_doctor을 제거 . 이것은 의사가 호출 될 때마다 다시 초기화됩니다. 난 당신이 new 방법에서만 이것을 원한다고 가정합니다. 내가 제대로 읽을 것, 당신은

@client.build_doctor unless @client.doctor.present? 
+0

가 미안 ... 난 단지 여기에 조금 혼란스러워 할 것 같은 무언가가 클라이언트가 할 수 않는 show없이 edit/new

또는, 한 의사가있어서 새로운 의사를 추가 할 수있는 링크가 없으므로 이제 전체 뷰 코드를 추가하고 has_many 연관 대신 has_one을 사용했습니다. 나는 이것이 내가 이해하지 못하는 것이 분명하다고 생각한다. 일단 사용자가 해당 양식 페이지를 작성하고 다음 페이지로 이동하면 의사를 구해야하고 그게 바로 클라이언트의 단일 연관체인가? – DanRio

+0

죄송합니다. 'has_one'이 cocoon/link_to_add_association과 관련하여 다소 혼란 스럽기 때문에, 정말로 질문을 철저히 읽지 않았습니다. 당신의 코드를 보았을 때, 고치는 의사의 "리셋"을 일으키는 것이 아니라,'show' 메소드의'build_doctor' 라인입니다. 그에 따라 내 대답이 업데이트되었습니다. – nathanvda

+0

잠깐, 정확하게 읽으면'show'도'edit'로 사용하고 있습니다. 맞습니까? 내 대답을 다시 업데이트했습니다. – nathanvda