2014-06-26 60 views
0

我有一個模型,「委屈」。申訴可以附帶許多文件。文件可以與各種事物相關聯,因此它們是多態的。在rails控制器中保存文檔

這裏是委屈模型

class Grievance < ActiveRecord::Base 

    belongs_to :account 
    belongs_to :employee 

    has_many :documents, :class_name => "EmployeeDocument", :as => 'documentable' 
    accepts_nested_attributes_for :documents, :allow_destroy => true 
end 

委屈的節目頁面允許用戶上傳要與申訴相關的多個文檔。這工作得很好。

我正在重構另一個開發人員的代碼,並查看控制器中的更新操作。他的代碼看起來像這樣...

def update 
    @grievance = @employee.grievances.find(params[:id]) 

    update! { 
    flash[:notice] = 'Updated successfully' 
    redirect_to edit_employee_grievance_path(:employee_id => @employee.id, :id => @grievance, :tab_to_return_to => params[:tab_to_return_to]) and return } 
    render :form 
end 

雖然這工作正常,但我想重構它,基本上是爲了讓它在我學習時更具可讀性。所以我改變了這一點。

def update 
    @grievance = @employee.grievances.find(params[:id]) 

    if @grievance.save 
    flash[:notice] = "#{@grievance.grievance_type} record updated" 
    redirect_to employee_grievance_path(@employee, @grievance) and return 
    else 
    flash[:alert] = "There was a problem editing the record" 
    render :edit 
    end 

現在,我很欣賞他的代碼不止更先進,當然更簡潔,但什麼我想明白的是,爲什麼他的代碼成功保存的文件,而我沒有。我可以在日誌中看到表單將文檔的詳細信息傳遞迴控制器,因此它必須與更新代碼有關?

+0

你問它是否已經保存,但你真的保存嗎? – dax

+0

我認爲在代碼中移除'和return'也是安全的,因爲通常只需要防止出現雙重渲染或重定向錯誤。在您的版本中,由if/else語句處理。 –

回答

2

在您的版本中,@greivance在加載和保存之間沒有任何操作。

你缺少這樣的事情:

@grievance.update_attributes(params[:grievance]) 

這些PARAMS裏面是從設定的@grievance值的形式屬性,以及它的嵌套屬性保存附加文件。

其他開發人員的版本正在使用Inherited Resources,它會自動執行所有操作。它們只是覆蓋與InheritedResources默認值不同的功能。