rubyonrails-view在唯一性验证错误后错误地重新加载



尝试提交新的指导方针后,您在表单上看到错误消息(由于指导方针未通过验证)。。。@specificates的列表没有正确地重新加载(即,它只是说是/否,而不是在您提交错误之前可以看到的正确列表)。我搞不清哪一部分错了。。。

VIEWS_form.html.erb

<%= simple_form_for(@guideline, html: {class: "form-horizontal"}) do |f| %>
  <% if @guideline.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@guideline.errors.count, "error") %> prohibited this guideline from being saved:</h2>
      <ul>
      <% @guideline.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.input :title, label: 'Title (e.g. Asthma for under 12 months)' %>
  <%= f.input :specialty, as: :select, collection: @specialties %> 
  <%= f.input :hospital %>
  <%= f.input :content, as: :string, label: 'Link' %>

  <div class="form-actions">
    <%= f.button :submit, :class => "btn btn-info btn-large" %>
  </div>
<% end %>

指南_控制器.rb

 def new
    @guideline = Guideline.new
    @specialties = Guideline.order(:specialty).uniq.pluck(:specialty)
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @guideline }
    end
  end

def create
@guideline = current_user.guidelines.new(params[:guideline])

respond_to do |format|
  if @guideline.save
    format.html { redirect_to @guideline, notice: 'Guideline was successfully created.' }
    format.json { render json: @guideline, status: :created, location: @guideline }
  else
    @specialties = Guideline.order(:specialty).uniq.pluck(:specialty)
    format.html { render action: "new" }
    format.json { render json: @guideline.errors, status: :unprocessable_entity }
  end
end

结束

这是一个常见错误。在创建操作中,如果验证失败,您应该声明@specificates,因为这在新模板中是必需的。

def create
  @guideline = Guideline.new params[:guideline]
  if @guideline.save
  else
    # you need to declare @specialties here since it is needed in the new template
    # which you want to render
    @specialties = Specialty.all
    render :new
  end
end

相关内容

最新更新