Rails Custom Validations on Associations
I have a user. A user can have many tables. Actual, only 5.
In my table model I have
validate :max_tables
def max_tables
if user.tables.count > 5
errors[:base] << "You already have 5 tables."
end
end
This works all good and if I try to create a table and my user already has 5, I get a page that says
ActiveRecord::RecordInvalid in TablesController#create
Validation failed: You already have 5 tables.
But I don't get redirected back to the new table page with errors displaying nice开发者_如何转开发ly like I do if other validations aren't met. For some reason I'm getting stuck on this hard error page.
Any ideas?
EDIT: SOLVED
I was generating a short url in an after_create callback, and in there I was calling save!
Once I fixed that, All was good. So thanks @house9!
Use errors.add_to_base "You already have 5 tables."
- in my oldest and biggest app I use errors.add_to_base
and return false
- it could be that the return is not required, but I haven't tested it.
EDIT: SOLVED I was generating a short url in an after_create callback, and in there I was calling save!
Once I fixed that, All was good. So thanks @house9!
精彩评论