Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails中干燥给定代码_Ruby On Rails_Ruby On Rails 4_Model View Controller - Fatal编程技术网

Ruby on rails 如何在rails中干燥给定代码

Ruby on rails 如何在rails中干燥给定代码,ruby-on-rails,ruby-on-rails-4,model-view-controller,Ruby On Rails,Ruby On Rails 4,Model View Controller,我的控制器中有这个代码,它有点长。有谁能指导我如何干燥这个: def edit @employee = Employee.where(id: params[:id]).first unless @employee.profile @employee.build_profile end unless @employee.current_address @employee.build_current_address end un

我的控制器中有这个代码,它有点长。有谁能指导我如何干燥这个:

def edit
    @employee = Employee.where(id: params[:id]).first
    unless @employee.profile
      @employee.build_profile
    end
    unless @employee.current_address
      @employee.build_current_address
    end
    unless @employee.permanent_address
      @employee.build_permanent_address
    end
    unless @employee.emergency_contact
      @employee.build_emergency_contact
    end
    unless @employee.attachments
      @employee.attachments.build
    end
  end

在这种情况下,你可以借助模型

在控制器中

def edit
  @employee = Employee.find(params[:id])
  @employee.create_association_instance  
end
在employee.rb模型中创建新方法

def create_association_instance
  self.build_profile unless self.profile    
  self.build_current_address unless self.current_address
  self.build_permanent_address unless self.permanent_address    
  self.build_emergency_contact unless self.emergency_contact    
 self.attachments.build unless self.attachments 
end

防御性的编程通常很糟糕。您应该在数据库中有完整的有效条目,创建一个rake任务,并在需要时更新所有条目