0

我正在使用内联表单让用户将数据提交到表格(请注意,我使用 CSS 而不是 html 表格来实现这一点)。当模型中的验证返回错误时,我想使用 Bootstrap 错误类突出显示输入字段,并将错误消息放在适当的表单字段下方。我正在使用 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>

JS 中的logger.debug正在触发,所以我知道错误正在传递给 JS,但insertAdjacentHMTL()似乎没有工作。

4

1 回答 1

0

也许这不会回答您的问题,但我希望它有助于改进您的代码。

首先,根据您的代码,我猜您应该在模型用户中有一些这样的关联:

has_many :travels

在您的模型 Travel 中:

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

关于你的问题,你能澄清一下是"#tf_#{k}"什么吗?

于 2013-03-02T04:40:28.853 回答