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任务,并在需要时更新所有条目