【问题标题】:How to DRY my given code in rails如何在 Rails 中干燥我给定的代码
【发布时间】:2023-03-25 18:20:01
【问题描述】:

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

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

【问题讨论】:

  • 防御性编程通常很难闻。您应该在 db 中有完整的有效条目,创建一个 rake 任务并根据需要更新所有条目

标签: ruby-on-rails ruby-on-rails-4 model-view-controller


【解决方案1】:

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

在控制器中,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多