[英]How to DRY my given code in rails
我的控制器中有这段代码,它有点长。 谁能指导我如何进行干燥:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.