2013-03-02 49 views
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()似乎沒有工作。

回答

0

也許這不會回答你的問題,但我希望它可以幫助改善你的代碼。

首先,根據你的代碼,我想你應該有一些像這樣的關聯模型中的用戶:

has_many :travels 

而且在模型中旅遊:

belongs_to :user 

因此,爲了提高你的代碼,你可以在你的控制器有這樣的:

respond_to :js, only: [:create] 

def new 
@travel = current_user.travels.new 
end 

def create 
@travel = current_user.travels.new(params[:travel]) 
if @travel.save 
    flash[:notice] = "Successfully saved trip" 
    @travels = current_user.travels 
else 
    # I guess you should have some code here in case any validation fail. If you dont 
    # have validations for the model Travel, you don't need the if statement here. 
end 
end 

關於你的問題,你能CLAR ify什麼是"#tf_#{k}"