2010-11-25 2 views
0

을 나는 세 가지 모델는 자신의 속성을 가진 조인 테이블에 accepts_nested_attributes_for 사용 - 중복 행

class Outbreak < ActiveRecord::Base 
     has_many :incidents, :dependent => :destroy 
     has_many :locations, :through => :incidents 

     accepts_nested_attributes_for :incidents, :allow_destroy => true 
     accepts_nested_attributes_for :locations, :allow_destroy => true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } 

    end 

    class Incident < ActiveRecord::Base 
     belongs_to :outbreak 
     belongs_to :location 
    end 


    class Location < ActiveRecord::Base 
has_many :incidents 
has_many :outbreaks, :through => :incidents 

    accepts_nested_attributes_for :incidents, :allow_destroy => true 

    end 

형태의 매개 변수 (레일 2.3.8) 다음 한 것은 괜찮을 것 같다

"outbreak"=> { "locations_attributes"=> { "0"=> { "lon"=> "1.39", "placename"=> "wetwe", "hpu_id"=> "15", "postcode" => ","address_3 "=>" ","지역 "=" "1" = ""0 "=> {"subtype_id "=>"7 ","category_id "=>"1 ","detail "=>" " , "subcategory_id"=> "2"}} } }

Outbreak가 저장되면 인시던트 테이블 (조인 테이블)에 3 행이 생성되고 비상 발생 및 위치 테이블에는 하나의 행이 생성됩니다. - 어떻게 그냥해야 할

id outbreak_id location_id category_id subcategory_id subtype_id detail created_at updated_at 

57 23 NULL  1  2   7       2010-11-25 14:45:18.385905 2010-11-25 14:45:18.385905 
58 23 27   NULL  NULL  NULL NULL   2010-11-25 14:45:18.39828 2010-11-25 14:45:18.39828 
59 23 27   NULL   NULL  NULL  NULL   2010-11-25 14:45:18.403051 2010-11-25 14:45:18.403051 

이 때문에 매개 변수의 형식 중 하나 또는 방법 accepts_nested_attributes_for 여러이어야합니다 다음과 같이 사건 테이블에

행은 완전히 PARAMS에서 채워지지 않습니다 인시던트 테이블에 모든 매개 변수 정보가있는 단일 행이 입력됩니까?

것을 포기하고 도움을 인터넷에 게시하기 전에 더 많은 노력을 나에게 가르쳐주지 ^^ 난 내 자신의 질문에 대답했습니다 지금까지 이번 주

답변

2

두 번째 시간, 내 원래보고 후 여전히

질문 나는 제대로 대답 충분한 정보를 포함하지 않았다 - 제 (떨어져 모델의 설정에서 위로) 문제 아래 발발 컨트롤러 새로운 방법의 발발 생성자이었다

원래 Outbreaks_controller

def new 

    @outbreak = Outbreak.new 
    @outbreak.risks.build 
    //links locations directly to Outbreak instead of through Incidents 
    @outbreak.locations.build 
    @outbreak.incidents.build 

    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @outbreak } 
    end 
end 

수정 됨 이 확인을 작동하는 것 같다 세 가지 모델

class Outbreak < ActiveRecord::Base 
     has_many :incidents, :dependent => :destroy 
     has_many :locations, :through => :incidents 

     accepts_nested_attributes_for :incidents, :allow_destroy => true 


    end 

    class Incident < ActiveRecord::Base 
     belongs_to :outbreak 
     belongs_to :location 

     accepts_nested_attributes_for :location, :allow_destroy => true 
    end 


    class Location < ActiveRecord::Base 
     has_many :incidents 
     has_many :outbreaks, :through => :incidents 

    end 

def new 

    @outbreak = Outbreak.new 
    @outbreak.risks.build 
    //builds Incidents then a Location through that incident 
    @outbreak.incidents.build.build_location 

    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @outbreak } 
    end 
end 

변경 breaks_controller - 또한 행동과 활동 만들기 만 제공 중첩 된 PARAMS을 필요로

+0

감사합니다 이것에 대한 많은 도움이 될 수 있습니다뿐만 아니라 통해 ...하지만 당신이 작업을 생성하여 게시 할 수 있으며, 가능한 경우 양식 (정보 제공의 목적으로 만 사용)? – tbk

+0

물론 뭔가를 올려 놓으려고 노력할 것입니다 - 양식은 abit complex (중첩 된 부분 수)이므로 새로운 답으로 게시 할 것입니다. – Pasted

1

기본 양식을 작성 게시 : 발병 (모델이 작업을 수행합니다). (아이디어를 얻을 필요가보다 여기 아마 속성과 필드가 비록)

def create 

    @outbreak = Outbreak.new(params[:outbreak]) 
    @outbreak.user_id = current_user.id 

     respond_to do |format| 
    if @outbreak.save 
     flash[:notice] = 'Outbreak was successfully created.' 
     format.html { redirect_to(@outbreak) } 
     format.xml { render :xml => @outbreak, :status => :created, :location => @outbreak } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @outbreak.errors, :status => :unprocessable_entity } 
     end 
    end 
end 

발발 양식 언급 한 두 섹션에 꽤 오래 그래서 아래로 절단 한 것입니다.

중첩 된 필드에 대한 HTML 요소 ID의 예는 Javascript의 observe_field 도우미 하단에 있습니다. 내가 함께 양방향 매핑으로 struggeling 이대로가 nested_attributes_for 파셜의 AJAX 업데이트에 만든 게시물 또한, AJAX update of accepts_nested_attributes_for

<% form_for(@outbreak, :html => {:multipart => true}) do |form| %> 
    <%= form.error_messages %> 
    <div id="tabs"> 
     <ul> 

      <li ><a href="#tabs_b">Outbreak</a></li> 
      <li ><a href="#tabs_c">Location</a></li> 

     </ul> 


      <div id="tabs_b"> 
       <fieldset id="b" class="form_div"> 
        <legend>Outbreak</legend> 

        <fieldset> 
         <legend>References</legend> 
         <div class="left_form"> 
         <%= form.label :user_reference %> 
         </div> 
         <div class="right_form"> 
         <%= form.text_field :user_reference %> 
         </div> 
         <div style="clear:both;"></div> 

        </fieldset> 

       </fieldset> 
      </div> 
      <div id="tabs_c"> 
       <fieldset id="c" class="form_div" > 

        <legend>Location</legend> 
         <div id="location_error"></div> 
          <fieldset> 
          <legend>Setting</legend> 
       <% form.fields_for :incidents do |incident_form| %> 

            <div class="left_form"> 
            <%= incident_form.label :category_id %> 
            </div> 

            <div class="right_form"> 
            <div id="incident_category_select"> 
            <%= render :partial => 'category_select', :locals => {:categories => @categories, :incident_form => incident_form} %> 
            </div> 
            </div> 
            <div style="clear:both;"></div> 

            <div class="left_form"> 
            <%= incident_form.label :subcategory_id %> 
            </div> 
            <div class="right_form"> 
            <div id="incident_subcategory_select"> 
            <%= render :partial => 'subcategory_select', :locals => { :subcategories => @subcategories, :incident_form => incident_form } %> 
            </div> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= incident_form.label :subtype_id %> 
            </div> 
            <div class="right_form"> 
            <div id="incident_subtype_select"> 
            <%= render :partial => 'subtype_select', :locals => { :subtypes => @subtypes, :incident_form => incident_form } %> 
            </div> 
            </div> 
            <div style="clear:both;"></div> 
            <div id="cuisine_div"> 
            <% if @outbreak.outbreak_type == "FOODBORNE" %> 
             <div class="left_form"> 
              <%= label :incident, :cuisine_id %> 
             </div> 
             <div class="right_form"> 
              <% cuisine_select = (@incident != nil ? @incident.cuisine_id.to_i : '') %> 
              <%= incident_form.select(:cuisine_id, "<option value='' >Please select</option>" + options_from_collection_for_select(@cuisines, :id, :name, cuisine_select)) %> 
             </div> 
            <% end %> 

            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= incident_form.label :detail %> 
            </div> 
            <div class="right_form"> 
            <%= incident_form.text_field :detail %> 
            </div> 


         </fieldset> 
         <fieldset> 
          <legend>Details</legend> 
          <% incident_form.fields_for :location do |location_form| %> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :placename %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :placename %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :address_1 %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :address_1 %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :address_2 %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :address_2 %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :address_3 %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :address_3 %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :town %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :town %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :postcode %> 
            </div> 
            <div class="right_form"> 
            <%= location_form.text_field :postcode %> 
            </div> 
            <div style="clear:both;"></div>   
            <div class="left_form"> 
            <%= location_form.label :region_id %> 
            </div> 
            <div class="right_form" > 
             <% region_select = (@location != nil ? @location.region_id.to_i : '') %> 
            <%= location_form.select(:region_id, "<option value=''>Select a region</option>" + options_from_collection_for_select(@regions, :id, :name, region_select)) %> 
            </div> 
            <div style="clear:both;"></div> 
            <div class="left_form"> 
            <%= location_form.label :hpu_id %> 
            </div> 
            <div class="right_form" > 
            <% hpu_select = (@location != nil ? @location.hpu_id.to_i : '') %> 
            <%= location_form.select(:hpu_id, "<option value=''>Select a HPU</option>" + options_from_collection_for_select(@hpus, :id, :name, hpu_select)) %> 
            </div> 
            <div style="clear:both;"></div> 

           <%= location_form.hidden_field :lon, :value => '' %> 
           <%= location_form.hidden_field :lat, :value => '' %> 
           <%= hidden_field_tag :postcode_error, :value => '0' %> 
           <% end %> 
          </fieldset> 


        <% end %>  

       </fieldset> 

      </div> 


    </div> 
    <% end %> 

    <div style="clear: both; margin: 10px;"></div> 
    <%= observe_field(:outbreak_incidents_attributes_0_location_attributes_postcode, 
       :url => { :controller => :locations, :action => :find_lonlat }, 
       :on => "onchange", 
       :loading => "Element.show('loader')", 
       :success => "Element.hide('loader')", 
       :with => "'postcode=' + encodeURIComponent($('outbreak_incidents_attributes_0_location_attributes_postcode').value)") %>