Limiting the number of related records (has_many, but max number?)

Can you limit the number of related records a given parent record has?

Example. Class/Student relatoinship. A Class has_many students but I want to limit the size of a class to a max 30 (of course minimum or exact numbers would hopefully work the same way?)

Can you limit the number of related records a given parent record has?

Example. Class/Student relatoinship. A Class has_many students but I want to limit the size of a class to a max 30 (of course minimum or exact numbers would hopefully work the same way?)

There may be a better way but I would just use a validation that prevents further students being added to the class when the limit is released.

By the way, can a student be in more than one class? If so then you need has and belongs to many or (which I prefer) has many through.

Colin

Colin

Thanks for your answer. The student/class thing was just an example - the actual stuff I’d be building has nothing to do with students and classes it was just the easiest thing that came to me.

You can do a validation on a total number of related records? I did not know that.

Colin

Thanks for your answer. The student/class thing was just an example - the actual stuff I'd be building has nothing to do with students and classes it was just the easiest thing that came to me.

You can do a validation on a total number of related records? I did not know that.

You can write a custom validation to do anything you like. The world is your mollusc.

Colin

I did not know you could write custom validations. Still learning

... which probably means you are ignoring an extremely valuable learning resource: the Rails Guides.

e.g. Active Record Validations — Ruby on Rails Guides

HTH,

Admittedly I haven’t gotten through all of them as I’m still working through the basics…