2014-06-26 63 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默认值不同的功能。