开发者

Rails Custom Validations on Associations

开发者 https://www.devze.com 2023-03-25 13:30 出处:网络
I have a user. A user can have many tables. Actual, only 5. In my table model I have validate :max_tables

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号