2014-10-09 112 views
0

我正在嘗試通過ajax呈現表單。它適用於創建新場地,但在嘗試編輯現有場地時,場地數據應加載到表單中。表單(_modal)在編輯場地鏈接被調用時呈現,但表單將作爲新表單處理,並且所有字段均爲空白。在binding.pry調用@venue,我們看到正確的場地對象。通過ajax呈現編輯表單

我該如何將表單處理爲編輯而不是新建?思路:

  • respond_to do |format| 
         format.js { *do stuff* } 
    
  • 添加更多的參數,以形成?

  • 做手工 - 改變形式的屬性和/或數據與jQuery補

感謝任何建議!

_modal.html.erb:

<section id="venue-modal" class='modal' title="Venue Form" class=""> 
    <%= simple_form_for(@venue, remote: true) do |v| %> 
    <div id='closeButton'><a href='#'>x</a></div> 
    <% binding.pry %> 
    <%= v.input :name, label: "Venue Name" %> 
    <%= v.input :city %> 
    <%= v.input :state, collection: States.us_states %> 

    <div class="actions"> 
     <%= v.submit 'Submit', class: 'button' %> 
    </div> 
    <% end %> 
</section> 

呈現以下HTML:

<form accept-charset="UTF-8" action="/venues" class="simple_form new_venue" data-remote="true" id="new_venue" method="post"> 

鏈接調用模式:

<%= link_to edit_venue_path(venue), :remote => true, :class => "edit_venue_link" do %> 

控制器:

def edit 
    id = params[:id] 
    if id == 'new' 
    @venue = Venue.new 
    else 
    @venue = Venue.find(id) 
    end 
end 

Venue.js:

$('.edit_venue_link').on("ajax:success", function(e, data, status, xhr) { 
// stuff happens 

回答

1

更換模式內容與這行代碼在modal.js.erb:

$('#venue-modal').html("<%= escape_javascript(render partial: 'venues/modal') %>"); 

控制器:

def edit 
    id = params[:id] 

    if id == 'new' 
    @venue = Venue.new 
    else 
    @venue = Venue.find(id) 
    end 
    respond_to do |format| 
    format.js { render 'venues/modal' } 
    end 
end 

區段標記遷出的模態部分。表單然後識別@venue並且字段適當地加載。