Recently I have faced with a situation when there was a need to build custom validation for a single controller action. Let’s say we have a User model with a role attribute. Administrator should have an ability to create a users(in protected area) with any role. And any guest should have an access to the public registration page, where he can select his role from the limited list of the registerable roles. So how can we implement a validation, which will work correctly for both administrator and public user registration pages? My solution described below.
classUser<ActiveRecord::Basevalidate:ensure_correct_roleclass<<selfdefall_roles# here goes a full list of available roles enddefprotected_roles# and this is protected list of roles which should not be registerable through public pageenddefregisterable_rolesall_roles-protected_rolesendenddefrestrict_roles@roles_restricted=trueenddefroles_restricted?@roles_restrictedendprivatedefensure_correct_rolerole_valid=ifroles_restricted?role.in?(User.registerable_roles)elserole.in?(User.all_roles)enderrors.add(:role,'is invalid')unlessrole_validendend