我将 Twitter Bootstrap 与我的 rails 3.1 应用程序一起使用。在我的 Timesheet#show 页面上,我有一个模式框,显示用于添加嵌套记录的表单。提交时,对 create.erb.js 进行 Ajax 调用,并创建记录并将其添加到 . 表单向数据库提交了两条记录,但 Ajax 不工作且表单未清除。
在我看来:
<button class="btn primary" data-controls-modal="modal-from-dom" data-backdrop="true" data-keyboard="true">New Run</button>
模态(new.html.erb)
<div id="modal-from-dom" class="modal hide fade in">
<div class="modal-header">
<a href="#" class="close">×</a>
<h3>Add a Run</h3>
</div>
<div class="modal-body">
<%= form_for ([@timesheet, @timesheet.runs.new]), :remote => true do |f| %>
<fieldset>
<%= f.label 'Select an athlete'%>
<div class="input"><%= f.collection_select(:athlete_id, Athlete.all, :id, :name_with_comma, :prompt => 'Choose...' )%></div>
</fieldset>
<% @timesheet.eyes.each do |eye| %>
<%= f.fields_for "splits_attributes[]", Split.new do |s| %>
<fieldset>
<%= s.label :time, eye.name %>
<div class="input"><%= s.text_field :time, :class => 'span2' %></div>
<%= s.hidden_field(:eye_id, :value => eye.id) %>
</fieldset>
<% end %>
<% end %>
</div>
<div class="modal-footer">
<%= f.submit :class => 'btn primary' %>
<a href="#" class="btn secondary">Secondary</a>
</div>
<% end %>
</div>
控制器 RunsController.rb
def create
@run = @timesheet.runs.new(params[:run])
@run.position = @run.athlete.runs.find_all_by_timesheet_id(@run.timesheet).count + 1 # auto increment the run position
if @run.save
respond_to do |format|
format.html {redirect_to @timesheet, :notice => "Run added"}
format.js
end
else
redirect_to @timesheet, :alert => "Unable to add run"
end
end
创建.js.erb
$("#splits-table").append("<%= escape_javascript(render(@run)) %>");
$("#run_<%= @run.id %>").effect("highlight", {}, 3000 )
$("#new_run").reset();
最后,Bootstrap-modal.js 提供了什么:
$(document).ready(function () {
$('body').delegate('[data-controls-modal]', 'click', function (e) {
e.preventDefault()
var $this = $(this).data('show', true)
$('#' + $this.attr('data-controls-modal')).modal( $this.data() )
})
})
如前所述,当我填写表单并提交时,两条相同的记录被保存到数据库中,并且模式保持在原位,其中的值仍在其中。我究竟做错了什么?