Habtm, multi select, and validation

Greetings -

I’m trying to find the most efficient, “Rails” way to solve the
following problem. It’s in two parts, but I think the solution is
somewhat related:

I have Recipe and Category model related by HABTM. I would like to

1.) Validate the number of categories associated with a recipe, say a
minimum of 1 and a max of 3. (So validates_associated will not work
here, right?)

2.) In the view, present a select box with a prompt in it, e.g. “Choose
1 to 3 of the following categories”, as the first option. I’ve found
ways to get this to work with the :prompt method in a 1-to-many
relationship, but I haven’t found anything to work with a HABTM

I’ve solved #1 with a controller hack that feeds the number categories
to a recipe accessor and then validating that, but that seems so …

Any suggestions, pointers?


On Tuesday, June 20, 2006, at 8:08 PM, Lance D. wrote:

here, right?)
Any suggestions, pointers?


Posted via http://www.ruby-forum.com/.

Rails mailing list
[email protected]

a custom validate method should do the trick.

If you read through the validation docs in the API, it might give you
some info about this, and the AWDwR.


Just write a validate method in the Recipe class:

class Recipe < ActiveRecord::Base
def validate
errors.add_to_base “Please select between one and three categories
for the recipe” unless (1…3).include?(categories.size)


On 20 Jun 2006 18:47:30 -0000, Kevin O.

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