2013-02-20 49 views
0

當您嘗試提交新的指導方針,並在窗體上看到一條錯誤消息(由於指導方針正確驗證失敗)... @specialties列表不能正確重新載入(即它只是說出是/否,而不是你在提交錯誤之前看到的正確列表)。我不能_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 

末制定出哪一部分是錯在這裏...

VIEWS

回答

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 
+0

謝謝!非常高興我正在犯常見錯誤 - 這是令人奇怪的讓人放心的。已經在上面打印了我的正確創建操作,以防有人發現它有用。 – tessad 2013-02-20 11:47:39