0
我正在使用內聯表單向用戶提交數據到表(注意我使用CSS而不是html表來實現此目的)。當模型中的驗證返回錯誤時,我想使用Bootstrap錯誤類來突出顯示輸入字段,並將錯誤消息放在適當的表單域下面。我使用AJAX提交表單。錯誤顯示在rails中的ajax表單不起作用
我有問題,這是我到目前爲止有:
控制器:
def create
@travel = Travel.new(params[:travel])
@travel[:user_id] = current_user.id
convert_date # and return
if @travel.save
flash[:notice] = "Successfully saved trip"
@travels = Travel.where("user_id = ?",current_user)
respond_to { |format| format.js }
end
end
JS觀點:
<% if @travel.errors.any? %>
<% @travel.errors.full_messages.each { |msg| logger.debug(msg) } %>
<% @travel.errors.messages.each do |k,v| %>
<% logger.debug("#tf_#{k}") %>
$(<%= "#tf_#{k}" %>).insertAdjacentHTML("afterbegin","<span class="control-group error"><span class="controls">");
$(<%= "#tf_#{k}" %>).insertAdjacentHTML("beforeend","</span></span>");
$(<%= "#error_#{k}" %>).val("<%= "#{k} #{v}" %>");
<% end %>
<% else %>
$(":input:not(input[type=submit])").val("");
$("#travels_list").html("<%= escape_javascript(render(:partial => "travels")) %>");
<% end %>
形式分:
<%= form_for @travel, :remote => true, :html => {:class => "form-inline", :id => "new-travel-form"} do |f| %>
<div class="row-fluid">
<span id="tf_city"><%= f.text_field :city, :placeholder => "London, UK", :class => "span3" %></span>
<span id="tf_arrive_date"><%= f.text_field :arrive_date, :class => "span2" %> </span>
<span id="tf_leave_date"><%= f.text_field :leave_date, :class => "span2" %> </span>
<span id="tf_notes"><%= f.text_field :notes, :placeholder => "e.g. staying at the Hilton", :class => "span3" %></span>
<%= f.submit "save", :class => "btn btn-primary span1" %>
</div>
<% end %>
<div class="row-fluid error" id="error_expl">
<span id="error_city" class="help-inline span3"></span>
<span id="error_arrive_date" class="help-inline span2"></span>
<span id="error_leave_date" class="help-inline span2"></span>
<span id="error_notes" class="help-inline span3">test</span>
</div>
The在JS中正在解僱,所以我知道錯誤正在傳遞給JS,但insertAdjacentHMTL()
似乎沒有工作。