2012-08-04 41 views
1

我有2個控制器:DocumentsControllerDashboardController
用戶登錄成功後,他被重定向到dashboard_path,其中有一個窗體創建「快速文件」這樣如何從另一個控制器捕獲mongoid驗證錯誤?

<%= form_for @document, :html => {:class => 'well'} do |f| %> 
     <% if @document.errors.any? %> 
     <div id="alert alert-block"> 
      <div class="alert alert-error"> 
      <h2>Couldn't create your doc. :(</h2> 

      <ul> 
      <% @document.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
      <% end %> 
      </ul> 
      </div> 
     </div> 
     <% end %> 
     <label>A lot of fields</label> 
     <%= f.text_field :fields %> 

     <div class="form-actions"> 
     <%= f.submit 'Create document', :class => 'btn btn-large' %> 
     </div> 
    <% end %> 

但之後,當異常發生(如用戶忘記填寫場),我想表現出這些異常,不只是一個警告說「錯誤」 ...其實,我沒有找到一個辦法做到這一點

這裏是我的DashboarController

class DashboardController < ApplicationController 
    before_filter :authenticate 
    def index 
    @document = Document.new 
    end 
end 

和我DocumentsController

class DocumentsController < ApplicationController 
    respond_to :json, :html 
    def show 

    end 

    def create 
    @document = Document.new(params[:document]) 
    @document.user = current_user 

    if @document.save 
     redirect_to dashboard_path, notice: 'Created!' 
    else 
     flash[:error] = 'Error!' 
     redirect_to dashboard_path 
    end 
    end 

end 

任何幫助表示讚賞:)

回答

1

您正確成功重定向;但如果失敗,則不應重定向;您需要在填充表單的位置呈現模板。

if @document.save 
    redirect_to dashboard_path, notice: 'Created!' 
else 
    render 'dashboard/index' 
end 

你必須確保由索引模板所需的所有變量都在documents_controller(你只是渲染指數模板的創建操作可用;你不是從運行的代碼儀表板控制器的索引操作)。下面是Rails相關指南的摘錄:

使用render with:action對於Rails新手來說,它經常是混淆的來源。指定的動作用於確定要呈現哪個視圖,但Rails不會在控制器中運行該動作的任何代碼。在調用render之前,必須在當前操作中設置視圖中所需的任何實例變量。

更多的http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

+0

工作就像一個魅力...但我在想......我的用戶可以創建從他dasboard文件(一個快速的文件,就像我說的),或者他可以創建更復雜從「新文檔」鏈接獲取文檔(填充更多字段)。我該如何處理?在這個「新文檔」中,我不想再次呈現儀表板 – 2012-08-04 02:43:55

+1

將登錄名置於部分內容中。然後渲染該部分。或者,讓create action返回一個@ document.to_json並處理包含該表單的任何代碼中的對象。 – 2012-08-04 03:08:26

+0

謝謝,你救了我的一天:D – 2012-08-04 03:14:14