我的控制器中有这个代码,而且有点长。任何人都可以指导我如何干这个:
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
答案 0 :(得分:2)
在这种情况下你可以帮助模型,
在控制器中,
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