Reputation: 5320
I'm looking to see if there is a smart way to do something like the following...
In my app I have projects. I want to prevent a user from adding more than 10 projects. My understand after only having used rails for a few weeks is, that I should make a helper in my model for this, does that sound right?
Also should I do this at the model/helper level or is this something that should be done for all models with some type of setting file?
So the idea is, when the user goes to create a new project, before_create, it checks, if the user has 10+ projects already, is says, sorry not at this time? ALso, interested in how to output the error msg, but 1 step at a time for a newbie.
thanks
Upvotes: 0
Views: 507
Reputation: 211540
Doing this as a validation method is pretty straightforward. In Rails 3 you just declare a method to be run during validation and it has an opportunity to add errors if the situation arises:
class Project
validate :user_can_create_projects
protected
def user_can_create_projects
if (user and user.projects.count >= 10)
errors.add_to_base("You have created too many projects.")
end
end
end
This is not an entirely bullet-proof method as there is a very small chance that someone might be able to create a project between the interval when you check the count and when you actually create the project. That sort of thing has a much greater chance of happening when someone double-clicks a form submit button, for instance, but in practice is relatively rare.
Upvotes: 3