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?)

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.

On 1 July 2015 at 16:51, John L. [email protected] wrote:

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

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

On 1 July 2015 at 17:16, John L. [email protected] wrote:

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

On Wed, Jul 1, 2015 at 10:40 AM, John L. [email protected] wrote:

I did not know you could write custom validations.

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

e.g. http://guides.rubyonrails.org/active_record_validations.html

HTH,

Hassan S. ------------------------ [email protected]
http://about.me/hassanschroeder
twitter: @hassan
Consulting Availability : Silicon Valley or remote

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs