尝试提交新指南后,您在表单上看到错误消息(由于指南正确无法通过验证)... @specialties列表未正确重新加载(即它只是说是/否而不是您提交错误之前可以看到的正确列表)。我无法弄清楚哪一部分是错的......
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 %>
guidelines_controller.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
端
答案 0 :(得分:1)
这是一个常见的错误。在您的创建操作中,如果验证失败,则应声明@specialties,因为新模板中需要验证。
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