2017-04-01 79 views
0

我有一個has_many通過關聯,我試圖設置一個嵌套窗體,允許通過javascript創建新的連接/子記錄而不會離開父窗體/頁。下面的代碼對集合被渲染的標準表單起作用,但我不確定這個嵌套表單示例中缺少什麼。Rails將新的has_many通過連接記錄添加到嵌套窗體通過javascript

型號:

class FullApplication < ApplicationRecord 
    has_many :fullapplication_districts, inverse_of: :full_application, dependent: :destroy 
    has_many :districts, through: :fullapplication_districts 

    accepts_nested_attributes_for :fullapplication_districts 

class FullapplicationDistrict < ApplicationRecord 
    belongs_to :full_application 
    belongs_to :district 

    validates_presence_of :full_application, :district 
end 

class District < ApplicationRecord 
    has_many :fullapplication_districts, inverse_of: :district, dependent: :destroy 
    has_many :full_applications, through: :fullapplication_districts 
end 

查看:

<%= form_for(@full_application, url: full_applications_edit_path, method: :put) do |f| %> 
    <div id="fullapplicationdistrictlist" class='row'> 
    <%= f.fields_for :fullapplication_districts do |fad| %> 
     <%= fad.collection_select :district_id, District.all, :id, :name, {include_blank: true}, {class: 'form-control'} %> 
     <%= fad.number_field :percent_one, class: 'form-control', step: :any %> 
     <%= fad.number_field :percent_two, class: 'form-control', step: :any %> 
     <%= fad.number_field :percent_three, class: 'form-control', step: :any %> 
     <%= link_to full_applications_districts_path(:id), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %> 
     <i class="fa fa-trash"></i> 
     <% end %> 
    <% end %> 
    </div> 
<% end %> 
<%= link_to "Add New District", full_applications_districts_new_path(fullapplication_id: @full_application.id), method: :post, remote: true, class: "btn btn-form btn-primary", role: "button", data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Creating..."} %> 

fullapplication_districs_controller

def create 
    @full_application = FullApplication.find(params[:fullapplication_id]) 
    @fullapplication_district = FullapplicationDistrict.new(full_application_id: @full_application.id, district_id: District.first.id, percent_one: 0.0, percent_two: 0.0, percent_three: 0.0) 
    respond_to do |format| 
     @fullapplication_district.save 
     format.js 
    end 
    end 

create.js.erb

$('div#fullapplicationdistrictlist').append("<%= escape_javascript(render @fullapplication_district) %>"); 

非常感謝任何見解。

回答