For the sake of example let’s say you have an application where users list their ducks for sale. The services offers two Plans: Bronze, which allows you to list 3 ducks at a time; and Platinum, which allows you to list an unlimited number of ducks.
To handle this logic in the model we add a custom validation to check if user.current_ducks_listed > user.plan.max_number_of_ducks, and throw an error accordingly.
Ideally, we don’t want the problem to get this far. It’s best to prevent the user from adding a duck if he has reached his limit. This introduces a chunk of logic whose place isn’t quite clear. Let’s put it in the controller:
@user = current_user
max_ducks = @user.plan.max_number_of_ducks
duck_count = @user.ducks.count
flash[notice: “You have reached your limit. Upgrade your plan.”] if duck_count > max_ducks
@duck = Duck.new
We repeat this logic in the create action. Then, to stay DRY, move this logic to a before_filter that runs on new and create. We are still duplicating the model logic in the controller, though. And what if plans get more complex? This will add bloat to the controller method, and will require updates to the model, the controller, and possibly the view. Also, there’s the question of handling the visual side of this: do we hide the form from the user? If so how?
Is this about how everyone handles this type of scenario? Or is there a better way? Bearing in mind I’m two weeks into my Rails and Ruby studies, perhaps there’s a much better way? How would you handle visual feedback to the user?