Move some codes from controller to model