mercredi 13 juin 2018

Rails: Design pattern to modify params based on users type before passing on to model

There are mulitple controller actions that receive startDate as a parameter and pass it on to relevant models to fetch the data. Based on a user property, there are validation rules that has to be applied on this parameter. Validation wouldn't just fail, but instead assigns a default value specific to that user property.

The modification required on startDate is common across all the actions and should be applied in all the cases. So, i assume this logic shouldn't be repeated at each model. Instead, controller's before_action filter, something like filtered_params sounds the right place to do it.

before_action :filtered_params

def filtered_params
   params.require(:query).permit(:start_date)
   user = User.instance
   if(user.type == 'student') {} # startDate should be Greater than or equal to 12-03-2018. modify params.startDate with the logic
   elsif(user.type == 'professor') {} // startDate should be Greater than equal to 01-01-2018
   else {} // do nothing
   end
end

The above approach works, but i do not want to get stuck in if else loop. Is there a better way to do it ?

Aucun commentaire:

Enregistrer un commentaire