Rails:在尝试提交包含验证错误的表单时阻止表单重置

时间:2013-04-27 02:22:08

标签: ruby-on-rails

目前,当我提交具有valdidation错误的表单时,表单将重置为空值。有没有办法在字段中保留值,以便用户不必重新输入整个表单?

我的创建动作:

def create
  @quote = Quote.new(params[:quote])
  if @quote.save
    flash[:success] = "Record Created Successfully"

    redirect_to quotes_url
  else
    render 'new'
  end
end

我的表格:

<%= form_for @quote do |f| %>
<fieldset>
  <% if @quote.errors.any? %>
      <div id="errorExplanation">
        <h2><%= pluralize(@quote.errors.count, "error") %> prohibited this user from being saved:</h2>
        <ul>
          <% @quote.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
  <% end %>
  <p>
    <%= f.label :quote_date, "Date of Quote" %>  <br/>
    <%= f.text_field :quote_date %>
  </p>

  <p>
    <%= f.label :good_through %> <br/>
    <%= f.text_field :good_through %>
  </p>

  <p>
    <%= f.label :quote_number %><br/>
    <%= f.text_field :quote_number %>
  </p>
  <p>
    <%= f.label :customer_id, "Customer" %><br/>
    <%= select(:quote, :customer_id, Customer.all.collect {|c| [ c.fname, c.id ] }, :prompt => "Select Customer") %>
  </p>

  <%= f.fields_for :quote_items do |builder| %>
      <%= render 'quote_item_fields', :f => builder %>
  <% end %>

  <%= link_to_add_fields "Add Line Item", f, :quote_items %>

  <p>
    <%= f.submit %>
  </p>
</fieldset>

1 个答案:

答案 0 :(得分:0)

试试这个:

QuotesController#new

@quote = || Quote.new

这样你可以将带有失败参数的@quote实例变量从#create传递给'new'模板,并且不会被#new覆盖。

免责声明:我还没有在实际代码中验证这一点。只是想法